Java Client / Server - Using BufferedWriter instead of PrintWriter

In all the Java client / server examples, I saw the BufferedReader used to receive data, for example in

 BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

and PrintWriter to send data, for example, to

 PrintWriter writer = new PrintWriter(socket.getOutputStream()); 

But can I just use BufferedWriter instead of PrintWriter ? I need to send an unformatted client and String betweens server, so BufferedWriter should give better performance (this is not a problem).

+4
source share
3 answers

PrintWriter essentially provides convenience methods around Writer. If you do not need this convenience method, but you just need to write the characters, then functionally you can use any taste of the Writer created, including the "raw" OutputStreamWriter.

If you write characters one at a time and the socket stream is not buffered, then it would be wise to put some buffering somewhere using a BufferedWriter or wrapping a BufferedOuputStream around your original output stream. An example of where you usually do not need to do this is in the servlet, where the streams passed to your servlet are usually already buffered.

PrintWriter also has a “function” for catching exceptions for write methods, which you should then explicitly check with checkError () [hands up, who actually does this, and who just assumes the write succeeded ...]. This may or may not be desirable ...

+3
source

Of course you can use BufferedWriter . PrintWriter usually used for convenience , since it offers a good set of functions without additional exception handling (which often simplifies the examples). PrintWriter can also delegate its operations to BufferedWriter , if necessary.

Regarding performance, see javadocs for BufferedWriter

In general, Writer immediately sends its output to a base character or stream of bytes. If an invitation is not required, we recommend wrapping the BufferedWriter around any Writer whose write () operations can be expensive, such as FileWriters and OutputStreamWriters.

+2
source

What is wrong with PrintWriter? The match is made because of the convenient readLine / writeLine match. You do not have this convenience in BufferedWriter. You can also specify autoflush with your PrintWriter.
If you need a buffer, you can wrap a BufferedWriter in PrintWriter

 PrintWriter pw = new PrintWriter( new BufferedWriter( ... ) ); 
+2
source

Source: https://habr.com/ru/post/1342513/


All Articles