Encapsulate the Writer object into an OutputStream object

Source: Internet
Author: User

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 );
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.