Oria Gruber Oria Gruber - 6 months ago 11
Java Question

ObjectInputStream.readObject skips last line of text file

Fairly simple question, I have a server with some file, lets call it

serverFile.txt
and I wish to send it line by line to some client. to achieve this, i wrote this simple code on the server side

BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
while(line != null)
{
line = line + System.lineSeparator();
MMULogFileController.getOos().writeObject(line);
line = br.readLine();
System.out.println(line);
}
br.close();


where the MMULogFileController.getOos is the outputstream of the accepted socket.

It does indeed print all the lines of the file
serverFile.txt


My problem is on the client side. This is the relevant code -

ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
String line = (String)in.readObject();
File newLogFile = new File("newLog.txt");
PrintWriter ptofile = new PrintWriter(newLogFile.getName());
while(line != null)
{
ptofile.write(line);
try
{
line = (String) in.readObject();
}
catch(java.io.EOFException e)
{
line = null;
}
}
ptofile.close();


and it prints all the lines correctly into a new file on the client side, except for the very last line. I know it was sent from the server because it was printed, but on the client side it recieved null because it reaches EOF. Is there any way to deal with this?

Answer

Myself, I'd use a PrintStream to send the text out, and then read it in using either a BufferedReader or a Scanner. But having said that, if you insist on using an ObjectOutputStream, you should either flush or close it when done sending your file's text, and certainly close it when you're done using it.

Also, avoid this type of code:

catch(java.io.EOFException e)
{
    line = null;
}

since this means that you're completely ignoring your exceptions. At least view the stack trace.