嘿,我正在尝试使用 Java 套接字发送文件,但我在使用 InputStream 类的读取函数时遇到问题。我有这个代码
InputStream is = sock.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
byte [] buffer = new byte[4096];
int bytesRead;
int totalLength = 0;
while(-1 != (bytesRead = is.read(buffer))) {
bos.write(buffer, 0, bytesRead);
totalLength += bytesRead;
}
bos.close();
fos.close();
is.close();
但它在最后停止了。我已经用 System.err.println 和调试检查了这个,看起来 is.read 从来没有像缓冲区结束时那样给出 -1。 因此,例如我有一个有 5000 字节的文件,首先 read() 返回 4096,然后返回 4(文件的其余部分),然后没有任何内容会导致无限循环。可能是什么问题?
我真的很感谢你能提供的任何帮助,因为我现在已经被困在那里大约两个小时了。
最佳答案
read never gives -1 as it should when the buffer ends
这是不正确的。它不应该在缓冲区结束时返回 -1。它只会在 stream 结束时返回 -1,直到对等方关闭连接才会发生。
关于java - InputStream 读取不返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28961318/