【问题标题】:What does array of 1's mean in binary when reading读取时二进制1的数组是什么意思
【发布时间】:2020-11-07 13:13:13
【问题描述】:

当没有更多字节要读取时,为什么我会得到 32 位 1?当我使用 FileInput 流时。 我不应该得到 EOFException (就像我们在 ObjectData 流中得到)?

我将演示使用简单的读/写程序。

        try {
            FileWriter fileWriter = new FileWriter("a.txt");
            fileWriter.write('A');  //writes 'A' to file (a.txt)
            fileWriter.close();
        }catch (IOException ioe){
            ioe.printStackTrace();
        }

        try {
            FileInputStream fileInputStream = new FileInputStream("a.txt");
            System.out.println(Integer.toBinaryString(fileInputStream.read()));//1000001
            System.out.println(Integer.toBinaryString(fileInputStream.read()));//11111111111111111111111111111111
            System.out.println(Integer.toBinaryString(fileInputStream.read()));//11111111111111111111111111111111
            System.out.println(Integer.toBinaryString(fileInputStream.read()));//11111111111111111111111111111111
        }catch (IOException ioe){
            ioe.printStackTrace();
        }

所以在每个 read() 中我得到 4 个字节的 1。那是无限的.. 我以为我只会得到字节值,因为 65 在二进制中是 1000001。所以总共1个字节。 这些其他字节从何而来?它们真的存在吗?

编辑: 我计算时得到的这两个值有什么区别?那么为什么不直接抛出 EOFException 呢?

【问题讨论】:

  • 11111111111111111111111111111111-1 我可能认为它是 EOF 标志的二进制表示
  • 我刚刚从二进制到十进制计算了第 32 位。结果是 4294967295。然后我还从有符号 2 的补码中得到了十进制:-1。这是什么意思?
  • 较大的数字是无符号整数,另一个是Java使用格式的有符号整数。

标签: java io binary ascii filestream


【解决方案1】:

Java 使用称为2's complement 的系统以二进制表示有符号数。在这个系统中,数字 -1 用所有位都为 1 的位模式表示。这是因为将 1 加到所有位都已设置的数字上会得到零(感谢 overflow)。

所以您观察到fileInputStream.read() 返回 -1,这就是它表示“文件结束,没有更多内容可读取”的状态。

【讨论】:

    【解决方案2】:

    阅读文档! https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/FileInputStream.html#read()

    read()
    Returns:
        the next byte of data, or -1 if the end of the file is reached.
    

    【讨论】:

    • 是的,我知道,但小数点后的 8 不是 -1,而是 4294967295。请在计算器中尝试..
    • 在 Java 中,整数是有符号的。 32 位是-1。您的计算器可能假定为无符号整数。
    • 嗯,我去看看。说得通。无非如此,你知道它为什么会这样吗?为什么不像我们链接到 FileInputStream 的流那样抛出异常呢?如果我要循环它,我最终会陷入无限循环..
    • @AnaMaria:异常是针对错误情况的。到达InputStream 的末尾不是(必然)错误条件。
    • @Ana DataInputStream 和 ObjectInputStream 使用 EOFException 因为它们读取的数据结构比单个字节大。如果文件在“事物”的中间结束,则流需要有一种方式来传达它,那就是它们抛出 EOFException
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 2022-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多