• Post Reply Bookmark Topic Watch Topic
  • New Topic

While writing to a Socket, why is PrintWriter considered a standard choice over BufferedWriter?  RSS feed

 
John Drulo
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the advantage of using PrintWriter over BufferedWriter, when we are writing one String at a time?

Reference:pg 479 , Head First Java ,2nd Edition
 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't really compare the two as they do different things. In fact they are often used together when writing to files.
PrintWriter provides easy to use methods to output Strings, primitives and object types as well as providing methods for writing formatted strings whereas BufferedWriter provides a buffer to make writing to data sinks such as files more efficient.

The API docs for BufferredWriter include the following:
In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. For example,

will buffer the PrintWriter's output to the file. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also be aware of this issue: Don't println to a Socket
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!