0

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:

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. I cant figure out an ending clause for the while loop to reach. 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. Not a good way of doing it but has to be this way (I believe) when the data must be a String.

4

2 回答 2

1

我有一个客户端服务器程序,它必须将文件的内容作为字符串发送

为什么?馊主意。它应该作为字节发送。否则,您将面临数据损坏的风险。

并且无法决定如何结束包含该BufferedReader.read()方法的 while 循环

  1. 您根本不应该使用 a ,而BufferedReader应该使用 a BufferedInputStream,以避免文件包含文本的假设。
  2. 您应该在文件之前发送文件大小,并且您应该读取文件大小,然后循环直到您读取了那么多字节,或者您应该在发送文件后关闭套接字。
于 2013-03-21T02:57:13.930 回答
-1

如果您使用的是 BufferedReader,您可以尝试一次读取整行 ..

String line;
while((line = in.readLine()) != null) {
  // your code here
}
于 2013-03-21T02:47:11.463 回答