Fnr
Fnr

Reputation: 2274

Detect end of DataInputStream bytes not working (Java)

I'm using the class DataInputStream to read from a Socket. I must use the readByte (not readLine) because the input does not necessarily in String format. The problem is I must wait the end of the stream to call a function and I couldn't detect it.

The code:

reader = new DataInputStream(socket.getInputStream());
byte dt;            

String cmd = "";
while( (dt = reader.readByte()) >= 0){
    cmd += (char)dt;

    if( /* end of the stream reached */ ){ 
        processInput(cmd);
    }  
}
System.out.println("End of the loop");

The problem is I don't know how to write this if. And, the end of the loop is not being reached when the Stream ends, the proof of this is that the phrase "End of the loop" is never being printed, so it is just stuck on the loop

Upvotes: 1

Views: 1137

Answers (1)

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

This is documented at readByte()

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

So in order to see end of file, you must use try/catch

try {
    while(true){
        cmd += (char) reader.readByte();
    }
} catch (EOFException e) {
    // handle EOF
}

/* end of the stream reached */
processInput(cmd);

System.out.println("End of the loop");

An alternative would be to use one of the read() functions, which return -1 when reaching end of file, e.g.

int dt;
while ((dt = reader.read()) >= 0) {
// ...
}

Using one of the other read(...) functions could be more efficient, since they return a buffer full of input.

Upvotes: 4

Related Questions