Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

PrintWriter not printing to file  RSS feed

 
Michael Peal
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Some background:  I'm beginning a computer science grad program (I've self-taught myself basically everything I know; zero academic CS experience) and an assignment early on is to create a client-server application that allows the client to upload or download text files from the server.

I'm working on the upload part, where I have the client read the text file line-by-line (w/ a while-loop) through a buffered reader, then send those lines through to the server, which then uses a PrintWriter and another while-loop to write those same lines in to a file.

I've printed into the console to test and I can confirm the client is passing along the correct output.
I can also confirm the server is receiving that output and writing it correctly...except the loop seemingly doesn't end for some reason, so I can't pull out of the loop, close the PrintWriter (and save the file) and tell the client the upload is done.

The result is, I'm seeing the file created where I want it, but there is no content.

Here's the code:



Any help would be appreciated.
 
Stephan van Hulst
Saloon Keeper
Posts: 7804
142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Reading from a socket will only return null when the TCP connection termination handshake has been performed. That means your client should perform socket.shutdownOutput() after it's finished sending the contents of the file.

Another note, you should close your resources by using try-with-resources. Use the Files class to open a file writer. This is how it could look:

After the try-with-resources statement is finished, the socket, reader and writer will all automatically be closed.
 
Michael Peal
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan van Hulst wrote:Reading from a socket will only return null when the TCP connection termination handshake has been performed. That means your client should perform socket.shutdownOutput() after it's finished sending the contents of the file.

Another note, you should close your resources by using try-with-resources. Use the Files class to open a file writer. This is how it could look:

After the try-with-resources statement is finished, the socket, reader and writer will all automatically be closed.


Shutting down the output made all the difference.  Big thanks!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!