Convert PrintStream to PrintWriter

java, stream

Solution

To convert `PrintStream` to `PrintWriter`, use the constructor: `PrintWriter(OutputStream out)`

With that constructor, you risk getting the incorrect encoding, since `PrintStream` has an encoding but using `PrintWriter(OutputStream out)` ignores that and just uses the system's default charset. If you don't want the system default, you will have to keep the encoding in a separate field or variable and use:

pw = new PrintWriter(new OutputStreamWriter(myPrintStream, encoding));

Where `encoding` can be (for example) `"UTF-8"` or an instance of `Charset`.

Problem

Is there any possible way of converting `PrintStream` to `PrintWriter` (or vice versa) other than using `WriterOutputStream` which is in apache common?

Original source

Related problems