Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.io.EOFException when try to read from a socket

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)
like image 263
Yusuf1494 Avatar asked Jul 10 '13 07:07

Yusuf1494


1 Answers

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

like image 123
Evgeniy Dorofeev Avatar answered Nov 12 '22 09:11

Evgeniy Dorofeev