Java Client/Server - Using BufferedWriter instead of PrintWriter
In all examples of a Java client/server, I've seen BufferedReader
used for receiving data, like in
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
and Pri开发者_StackOverflow社区ntWriter
for sending data, like in
PrintWriter writer = new PrintWriter(socket.getOutputStream());
But can't I just use a BufferedWriter
instead of a PrintWriter
? I only need to send unformatted String betweens client and server, so a BufferedWriter
should give better performance (not that this is a problem).
PrintWriter essentially provides convenience methods around a Writer. If you don't need those convenience method-- but just need to write chars-- then functionally, you can use any flavour of Writer you choose, including a 'raw' OutputStreamWriter.
If you are writing chars one at a time, and your socket stream isn't buffered, then it would be advisable to put some buffering in somewhere, either by using a BufferedWriter or by wrapping a BufferedOuputStream around your raw output stream. An example of where you don't typically need to do this is in a servlet, where the streams passed to your servlet are typically already buffered.
PrintWriter also has the "feature" of swallowing exceptions on write methods, which you have to then explicitly check for with checkError() [hands up who actually does this, and who just assumes that the write succeeded...]. This may or may not be desirable...
Whats wrong with PrintWriter? The match is made because of the convenient readLine / writeLine match. You don't have that convenience in a BufferedWriter. Also you get to specify autoflush with your PrintWriter.
If you need the buffer you can wrap the BufferedWriter in a PrintWriter
PrintWriter pw = new PrintWriter( new BufferedWriter( ... ) );
Sure you can use a BufferedWriter
. PrintWriter
is commonly used for conveniance as it offers a good range of functions without the extra exception handling (which often makes the examples easier). The PrintWriter
could also delegate its operations to a BufferedWriter
if desired.
Regarding performance see the javadocs for BufferedWriter
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.
精彩评论