11

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

wattostudios
  • 8,666
  • 13
  • 43
  • 57
MBZ
  • 26,084
  • 47
  • 114
  • 191

1 Answers1

18

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.

matvore
  • 792
  • 6
  • 10
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • 3
    You can mock `System.out.println()` via `pw = new PrintWriter(System.out);` – Mr. Polywhirl Jan 13 '16 at 16:24
  • Better use the `OutputStreamWriter(OutputStream, Charset)` overload for UTF-8: `new OutputStreamWriter(myPrintStream, StandardCharsets.UTF_8)`. That way, you don't have to catch an UnsupportedEncodingException. – ComFreek Oct 25 '19 at 14:15