I created PrintWriter with autoflush function; why is it not autofluating?

My client is a web browser and sends a request to myserver using this URL: http://localhost

This is server side code. The problem is the run method of the ServingThread class.

 class ServingThread implements Runnable{ private Socket socket ; public ServingThread(Socket socket){ this.socket = socket ; System.out.println("Receives a new browser request from " + socket + "\n\n"); } public void run() { PrintWriter out = null ; try { String str = "" ; out = new PrintWriter( socket.getOutputStream() ) ; out.write("This a web-page.") ; // :-( out.flush() ; // :-( socket.close() ; System.out.println("Request successfully fulfilled.") ; } catch (IOException io) { System.out.println(io.getMessage()); } } } 

Am i using

 out = new PrintWriter( socket.getOutputStream(), true ) ; 

or

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

the output does not go to the browser. The output goes to the browser only if I manually flush the stream using

 out.flush() ; 

My question is: new PrintWriter( socket.getOutputStream(), true ) should automatically clear the output buffer, but it does not. Why?

+6
java io printwriter flush
source share
1 answer

From Javadocs :

Options:

out - output stream
autoFlush - logical; if true, println , printf or format methods will clear the output buffer

It does not say write() will clear the output buffer. Try using println() instead, and it should look as you expect.

+19
source share

All Articles