简体   繁体   English

使用BufferedReader.read()处理'file'的末尾

[英]Dealing with end of 'file' using BufferedReader.read()

I have a client server program which MUST send a file's content as a String and am having trouble deciding how to end the while loop containing the BufferedReader.read method.I have the code as: 我有一个客户端服务器程序,该程序必须以字符串形式发送文件的内容,并且在决定如何结束包含BufferedReader.read方法的while循环时遇到麻烦。我的代码为:

while((c = in.read()) != -1){                             
    fw.write((char)c);
    System.out.print((char)c);
}

But as it uses sockets, it never reaches -1 until the socket is closed. 但是由于使用套接字,直到套接字关闭,它永远不会达到-1。 I cant figure out an ending clause for the while loop to reach. 我无法弄清楚while循环要到达的结尾子句。 Are there any special characters? 有没有特殊字符?

Went with: 与:

while((line = in.readLine()) != null && !line.equals(BasicProtocol.SENDING_FILE_DONE))

where SENDING_FILE_DONE is a String which is added to the end of the stream. 其中SENDING_FILE_DONE是添加到流末尾的字符串。 Not a good way of doing it but has to be this way (I believe) when the data must be a String. 这样做不是一个好方法,但是当数据必须为String时,必须这样(我相信)。

I have a client server program which MUST send a file's content as a String 我有一个客户端服务器程序,该程序必须以字符串形式发送文件的内容

Why? 为什么? Bad idea. 馊主意。 It should be sent as bytes. 它应该作为字节发送。 Otherwise you are running the risk of data corruption. 否则,您将面临数据损坏的风险。

and am having trouble deciding how to end the while loop containing the BufferedReader.read() method 并且在决定如何结束包含BufferedReader.read()方法的while循环时遇到麻烦

  1. You shouldn't be using a BufferedReader at all, you should be using a BufferedInputStream , to avoid the assumption that the file contains text. 您根本不应该使用BufferedReader ,而应该使用BufferedInputStream ,以避免假设文件包含文本。
  2. You should have sent the file size ahead of the file, and you should read the file size, then loop until you have read exactly that many bytes, OR You should close the socket after sending the file. 您应该已经在文件之前发送了文件大小,并且应该读取文件大小,然后循环播放,直到您确切地读取了那么多字节为止,或者您应该在发送文件后关闭套接字。

If you are using BufferedReader, you can try reading the entire line at one go .. 如果您使用的是BufferedReader,则可以尝试一次读取整行。

String line;
while((line = in.readLine()) != null) {
  // your code here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM