尝试从套接字读取时出现 java.io.EOFException [英] java.io.EOFException when try to read from a socket

查看:29
本文介绍了尝试从套接字读取时出现 java.io.EOFException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么会出现 java.io.EOFException.我想在从服务器获取二进制流后写一个文件.

i don't know why java.io.EOFException appear. i want to write a file after i get binary stream from server.

这是我的代码

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,它说

DataInputStream.readByte API does not say it return -1 on EOS, it says

返回:此输入流的下一个字节作为有符号的 8 位字节.

Returns:the next byte of this input stream as a signed 8-bit byte.

抛出:EOFException - 如果此输入流已到达结尾.

Throws: EOFException - if this input stream has reached the end.

它假设在使用 DataInputStream.readByte 时我们知道流中剩余多少字节.否则我们可以使用 EOFException 作为 EOS 的指标.

It assumes that when working withh DataInputStream.readByte we know how many bytes are left in the stream. Otherwise we can use EOFException as an indicator of EOS.

顺便说一句,如果你使用 read() 你将在没有 EOFException 的情况下在 EOS 上得到 -1

BTW If you use read() you will get -1 on EOS without EOFException

这篇关于尝试从套接字读取时出现 java.io.EOFException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆