Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

Here's my code

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();

Stack trace

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

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

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...