从FileInputStream读取二进制文件

huangapple go评论59阅读模式
英文:

Reading Binary file from 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;
}
英文:

Getting null pointer exception when program enters while loop

        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;
        }

答案1

得分: 1

你假设每次读取都会读取16字节,而没有使用read返回的值。你应该重复使用字节数组,而不是将其设置为null。这就是导致空指针异常的原因。

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("已读取 " + offset / 16 + " 字节");
    offset += bytesRead;
    //b1 = null; // 这会将b1设置为null,这就是为什么下次在b1上调用read时会得到空指针异常
}
英文:

You are assuming 16 bytes are read with every read, instead of using the value returned by read. You also should just reuse your byte array and not set it to null. This is what's causing your 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
    }

答案2

得分: 0

好的,以下是翻译好的部分:

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

我完全不知道您为什么要将 b1 设置为 null。这就像那种“医生,我按这里会痛!”的事情。那么就别再按那里了。

删除这行 b1 = null

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

try (FileInputStream in1 = new FileInputStream(p1)) {
   ... 所有在 in1 上工作的代码放在这里
}
英文:

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.

I have absolutely no idea why you are setting b1 to null. One of those 'doctor, it hurts when I press here!' things. Stop pressing there then.

Delete the line b1 = null.

NB: You can't use inputstreams like this. The proper java usage is:

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

huangapple
  • 本文由 发表于 2020年8月29日 00:12:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63637446.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定