user6575289
user6575289

Reputation:

How is one byte read and returned as an int by read function in InputStream in java?

The read() function reads one byte at a time and the return type of this function is int. I want to know what happens under the hood so that byte is returned as an int. I have no knowledge of bitwise operators so can anyone answer in a way that i grasp it readily.

Upvotes: 0

Views: 1548

Answers (3)

vikash singh
vikash singh

Reputation: 1509

Below is the program to read one byte at a time using read() method of InputStream:

public class Main {
    public static void main(String[] args) {
        try {
            InputStream input = new FileInputStream("E:\\in.txt");
            int intVal;
            while((intVal = input.read()) >=0)
            {
                byte byteVal = (byte) intVal;
                System.out.println(byteVal);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Please not that the intVal here returned by input.read() is the byte value of the characters read from file in.txt.

Upvotes: 0

Stephen C
Stephen C

Reputation: 718826

It depends on the stream implementation. In some cases the method implementation is in native code. In others, the logic is simple; for example, in ByteArrayInputStream the read() method does this:

public class ByteArrayInputStream extends InputStream {
    protected byte buf[];
    protected int count;
    protected int pos;

    ...

    public synchronized int read() {
        return (pos < count) ? (buf[pos++] & 0xff) : -1;
    }
}

In other words, the bytes are converted into integers in the range 0 to 255, like the javadoc states, and -1 is returned at the logical end-of-stream.

The logic of buf[pos++] & 0xff is as follows:

  1. buf[pos++] is converted to an int
  2. & 0xff converts the signed integer (-128 to +127) into an "unsigned" byte (0 to 255) represented as an integer.

Upvotes: 4

JB Nizet
JB Nizet

Reputation: 691765

Under the hood, if the end of stream is reached, read() returns -1. Otherwise, it returns the byte value as an int (the value is thus between 0 and 255).

After you've verified that the result is not -1, you can get the signed byte value using

byte b = (byte) intValue;

That will just keep the 8 rightmost bits of the int, and the 8th bit from the right is used as the sign bit, thus leading to a signed value, between -128 and 127.

If the method returned a byte, there would be no way, other than throwing an exception, to signal that the end of the stream has been reached.

Upvotes: 3

Related Questions