我不知道为什么会出现java.io.EOFException。我想在从服务器获取二进制流后写入一个文件。
这是我的代码
inputStream = new DataInputStream(new BufferedInputStream(connection.getInputStream()));
FileOutputStream fos = new FileOutputStream("D:/Apendo API resumable download.txt");
byte b = inputStream.readByte();
while(b != -1){
fos.write(b);
b = inputStream.readByte();
}
fos.close();
堆栈跟踪
java.io.EOFException
at java.io.DataInputStream.readByte(DataInputStream.java:267)
at HttpRequestJSON.JSONRequest.sendRequest(JSONRequest.java:64)
at HttpRequestJSON.Main.main(Main.java:56)
最佳答案
DataInputStream.readByte API 没有说它在 EOS 上返回 -1,它说
返回:此输入流的下一个字节作为带符号的 8 位字节。
抛出:EOFException - 如果此输入流已到达末尾。
它假定在使用 h DataInputStream.readByte 时我们知道流中还剩下多少字节。否则我们可以使用 EOFException 作为 EOS 的指标。
顺便说一句,如果你使用 read() 你将在没有 EOFException 的 EOS 上得到 -1
关于尝试从套接字读取时出现 java.io.EOFException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17564556/