java中的InputStream中的read函数如何读取一个字节并作为int返回?

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

read()函数一次读取一个字节,return该函数的类型为int。我想知道引擎盖下发生了什么,所以字节被 returned 作为一个 int。我不了解按位运算符所以任何人都可以用我容易掌握的方式回答。

在引擎盖下,如果到达流的末尾,read() returns -1。否则,它 returns 作为 int 的字节值(因此该值介于 0 和 255 之间)。

验证结果不是-1后,您可以使用

获取带符号的字节值
byte b = (byte) intValue;

这将只保留 int 最右边的 8 位,右起第 8 位用作符号位,从而得到一个有符号的值,介于 -128 和 127 之间。

如果该方法返回一个字节,除了抛出异常之外,没有其他方法可以表明已到达流的末尾。

这取决于流的实现。在某些情况下,方法实现是在本机代码中。在其他情况下,逻辑很简单;例如,在 ByteArrayInputStream 中,read() 方法执行此操作:

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;
    }
}

换句话说,字节被转换为 0 到 255 范围内的整数,如 javadoc 状态,并在逻辑流结束处返回 -1。

buf[pos++] & 0xff的逻辑如下:

  1. buf[pos++] 转换为 int
  2. & 0xff 将有符号整数(-128 到 +127)转换为 "unsigned" 字节(0 到 255)表示为整数。

下面是使用 InputStream 的 read() 方法一次读取一个字节的程序:

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

请注意input.read()返回的intVal是从文件in.txt.

中读取的字符的字节值