【问题标题】:How is one byte read and returned as an int by read function in InputStream in java?java中的InputStream中的read函数如何读取一个字节并将其作为int返回?
【发布时间】:2017-12-12 12:17:18
【问题描述】:

read() 函数一次读取一个字节,该函数的返回类型是 int。我想知道幕后发生了什么,以便字节作为 int 返回。我对位运算符一无所知,所以任何人都可以用我容易掌握的方式回答。

【问题讨论】:

    标签: java stream inputstream


    【解决方案1】:

    下面是使用 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中读取的字符的字节值。

    【讨论】:

      【解决方案2】:

      这取决于流的实现。在某些情况下,方法实现是本机代码。在其他情况下,逻辑很简单。例如,在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++] &amp; 0xff的逻辑如下:

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

      【讨论】:

        【解决方案3】:

        在底层,如果到达流的末尾,read() 返回 -1。否则,它以 int 形式返回字节值(因此该值介于 0 和 255 之间)。

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

        byte b = (byte) intValue;
        

        这将只保留 int 的最右边 8 位,而从右边开始的第 8 位用作符号位,从而导致有符号值,介于 -128 和 127 之间。

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

        【讨论】:

          猜你喜欢
          • 2011-06-07
          • 2014-09-25
          • 2020-06-08
          • 2016-12-22
          • 1970-01-01
          • 2014-03-31
          • 1970-01-01
          • 2014-06-13
          相关资源
          最近更新 更多