相当简单的问题,我有一个带有一些文件的服务器,我们将其称为serverFile.txt
,我希望将其逐行发送到某个客户端。为了实现这一点,我在服务器端编写了这个简单的代码
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();
其中 MMULogFileController.getOos 是接受的套接字的输出流。
它确实打印了文件serverFile.txt
的所有行
我的问题出在客户端。这是相关代码 -
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();
并且它将所有行正确打印到客户端的新文件中,除了最后一行。我知道它是从服务器发送的,因为它已被打印,但在客户端它收到 null,因为它到达了 EOF。有什么办法可以解决这个问题吗?
最佳答案
我自己,我会使用 PrintStream 发送文本,然后使用 BufferedReader 或 Scanner 读取它。但话虽如此,如果您坚持使用 ObjectOutputStream,则应该在发送文件文本后刷新或关闭它,并且在使用完它后当然应关闭它。
此外,请避免使用此类代码:
catch(java.io.EOFException e)
{
line = null;
}
因为这意味着您完全忽略了异常。至少查看堆栈跟踪。
关于java - ObjectInputStream.readObject 跳过文本文件的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37624098/