new PrintWriter(new BufferedWriter(new PrintWriter(s.getOutputStream, true)))
-
27-10-2019 - |
Question
I am wondering is it possible to do
new PrintWriter(new BufferedWriter(new PrintWriter(s.getOutputStream, true)))
in Java where s is a Socket? Because it's impossible to create a BufferedWriter from an outputstream, I have wrapped the outputstream with a PrintWriter. But I want to buffer my print outs, so I wrap it with a BufferedWriter. But eventually I want to print using printWriter so I wrap it again with a PrintWriter. Is this legal in Java? Thanks!
Solution
It is legal but clumsy. You can buffer OutputStream
instead:
new PrintWriter(new BufferedOutputStream(s.getOutputStream), true)
Also have a look at the implementation of new PrintWriter(OutputStream, boolean)
:
public PrintWriter(OutputStream out, boolean autoFlush) {
this(new BufferedWriter(new OutputStreamWriter(out)), autoFlush);
}
buffering is already there!
OTHER TIPS
OutputStreamWriter
is the class you're looking for. Just pass it a stream and an encoding, for example "UTF-8"
.
new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream(), encoding)), true)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow