【问题标题】:Reading Binary file from FileINputStream从 FileINputStream 读取二进制文件
【发布时间】:2020-08-28 16:12:56
【问题描述】:

程序进入while循环时出现空指针异常

        File  p1 = new File("file.EXE");
        FileInputStream in1 = new FileInputStream(p1);
        byte[] b1 = new byte[16];
        int offset =0;
        while((in1.read(b1, offset, 16)) != -1) {
            System.out.println("read " + offset/16 + "bytes");
            offset += 16;
            b1 =null;
        }

【问题讨论】:

    标签: java file dependency-injection byte fileinputstream


    【解决方案1】:

    您假设每次读取都会读取 16 个字节,而不是使用 read 返回的值。您还应该只重用您的字节数组,而不是将其设置为空。这就是导致您的 NPE 的原因

        File  p1 = new File("file.EXE");
        FileInputStream in1 = new FileInputStream(p1);
        byte[] b1 = new byte[16];
        int offset =0;
        int bytesRead;
        while((bytesRead = in1.read(b1) != -1) {
            System.out.println("read " + offset/16 + "bytes");
            offset += bytesRead;
            //b1 =null; //this sets b1 to null and is why you get an NPE the next time you call read on b1
        }
    

    【讨论】:

    • read 的最后一个参数是长度,因此必须是 b1.length - offset 来表示缓冲区中的剩余空间。但是,当文件的字节数超过此缓冲区可以容纳的字节数(即超过 16 个)时,它将无限循环。
    【解决方案2】:

    嗯,第一次通过你说的循环:b1 = null,然后 while 循环通过评估条件重新启动,它将b1(现在为 null)传递给指定的方法,如果你这样做,你会得到一个NullPointerException

    我完全不知道您为什么将 b1 设置为 null。其中一位“医生,我按这里的时候很痛!”事物。那就别按那里了。

    删除b1 = null这一行。

    注意:您不能像这样使用输入流。正确的java用法是:

    try (FileInputStream in1 = new FileInputStream(p1)) {
       ... all code that works on in1 goes here
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-21
      • 2010-10-08
      • 2011-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2020-07-14
      • 2018-08-24
      相关资源
      最近更新 更多