从FileINputStream读取二进制文件

问题描述

程序进入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;
        }

解决方法

您假设每次读取都读取16个字节,而不是使用read返回的值。您还应该仅重用字节数组,而不要将其设置为null。这就是导致您的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
    }
,

好吧,第一次在循环中您说: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
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...