3

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!

Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
user700996
  • 463
  • 2
  • 10
  • 18

2 Answers2

4

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!

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
1

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) 
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245