Is there any possible way of converting PrintStream
to PrintWriter
(or vice versa) other than using WriterOutputStream
which is in apache common?
Asked
Active
Viewed 9,009 times
11

wattostudios
- 8,666
- 13
- 43
- 57

MBZ
- 26,084
- 47
- 114
- 191
-
Can't you use wrap PrintStream in PrintWriter? – nhahtdh May 27 '12 at 05:16
-
What is your objective ? – Bhavik Ambani May 27 '12 at 05:20
-
my objective is to convert printstream to print writer and NOT adding apache.jar to my code. – MBZ May 27 '12 at 05:21
-
For the other way round, see: https://stackoverflow.com/questions/4268353/is-there-a-simple-and-safe-way-to-convert-a-printwriter-into-a-printstream – fgb Jul 22 '17 at 23:41
1 Answers
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
.
-
3You 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