It isn't always easy. Just a quick summary for those who are still lost:
simple input stream
The read()
of an input stream just returns a value in range [0;255].
However, if no data is available, then it will return a -1
.
int value = inputStream.read(); // -1 if no data
If you would just cast this to a byte, then you are creating an overflow and you actually convert the range of [0;255] to a range of [-128;127].
byte signedValue = (byte) value;
data input stream
Now, if you wrap your InputStream
in a DataInputStream
then additional methods are available, such as the readByte()
method. This method will return a value in range [-128;127] because that is the range of the byte
type of java. Often you may want to convert it to a positive value.
If there is no data available, then of course a DataInputStream
cannot return -1
. So instead it will throw an EOFException
.
byte value = dataInputStream.readByte(); // throws EOFException
int positiveValue = value & 0xFF;
char character = (char) positiveValue;
PS: The DataInputStream offers some convenient methods that help you to read the values immediately in the correct value range.
int positiveValue = dataInputStream.readUnsignedByte();
int positiveValue = dataInputStream.readUnsignedShort();
socket input stream
But it can be more complex. If your initial input stream is actually a SocketInputStream
then no matter which method you use or how you wrap it, you will not receive -1
or EOFException
. Instead you will receive a SocketTimeoutException
.
socket.setSoTimeout(1000);
int value = socketInputStream.read(); // throws SocketTimeoutException
byte signedValue = (byte) value;
char character = (char) value;
There is just a little shortcoming in that last statement: Very rarely the read()
method of a SocketInputStream
will not return a SocketTimeoutException
in case of a timeout. It can actually return a -1
if the input stream is not correctly bound. In that case the connection is broken, and you need to close everything down and reconnect.