问题描述
程序进入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
}