简体   繁体   English

从 FileINputStream 读取二进制文件

[英]Reading Binary file from FileINputStream

Getting null pointer exception when program enters while loop程序进入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;
        }

You are assuming 16 bytes are read with every read, instead of using the value returned by read.您假设每次读取都会读取 16 个字节,而不是使用 read 返回的值。 You also should just reuse your byte array and not set it to null.您还应该重用您的字节数组,而不是将其设置为 null。 This is what's causing your NPE这就是导致您的 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
    }

Well, the first time through the loop you say: b1 = null and then the while loop restarts by evaluating the condition, which passes b1 (now null) to a method that is specced to state that if you do so, you get a NullPointerException .好吧,第一次通过循环你说: b1 = null然后 while 循环通过评估条件重新启动,它将b1 (现在为 null)传递给一个方法,该方法规定如果你这样做,你会得到一个NullPointerException .

I have absolutely no idea why you are setting b1 to null.我完全不知道您为什么将b1设置为 null。 One of those 'doctor, it hurts when I press here!'其中一位“医生,我按这里会痛!” things.事物。 Stop pressing there then.那就别按了。

Delete the line b1 = null .删除行b1 = null

NB: You can't use inputstreams like this.注意:您不能像这样使用输入流。 The proper java usage is:正确的java用法是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM