logo

将 Writer 对象包装成 OutputStream 对象

作者:Greg Wilkins 阅读:1123 发表于:2011-03-28 19:41:08

本代码源自网上:http://www.koders.com/java/fid5A2897DDE860FCC1D9D9E0EA5A2834CC62A87E85.aspx

Java 代码
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;


/* ------------------------------------------------------------ */
/** Wrap a Writer as an OutputStream.
* When all you have is a Writer and only an OutputStream will do.
* Try not to use this as it indicates that your design is a dogs
* breakfast (JSP made me write it).
*
@version 1.0 Tue Feb 12 2002
*
@author Greg Wilkins (gregw)
*/
public class WriterOutputStream extends OutputStream
{
    
protected Writer _writer;
    
protected String _encoding;
    
private byte[] _buf=new byte[1];
    
    
/* ------------------------------------------------------------ */
    
public WriterOutputStream(Writer writer, String encoding)
    {
        _writer
=writer;
        _encoding
=encoding;
    }
    
    
/* ------------------------------------------------------------ */
    
public WriterOutputStream(Writer writer)
    {
        _writer
=writer;
    }

    
/* ------------------------------------------------------------ */
    
public void close()
        
throws IOException
    {
        _writer.close();
        _writer
=null;
        _encoding
=null;
    }
    
    
/* ------------------------------------------------------------ */
    
public void flush()
        
throws IOException
    {
        _writer.flush();
    }
    
    
/* ------------------------------------------------------------ */
    
public void write(byte[] b)
        
throws IOException
    {
        
if (_encoding==null)
            _writer.write(
new String(b));
        
else
            _writer.write(
new String(b,_encoding));
    }
    
    
/* ------------------------------------------------------------ */
    
public void write(byte[] b, int off, int len)
        
throws IOException
    {
        
if (_encoding==null)
            _writer.write(
new String(b,off,len));
        
else
            _writer.write(
new String(b,off,len,_encoding));
    }
    
    
/* ------------------------------------------------------------ */
    
public synchronized void write(int b)
        
throws IOException
    {
        _buf[
0]=(byte)b;
        write(_buf);
    }