sandesh
sandesh

Reputation: 1

Reading Binary file from FileINputStream

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

Upvotes: 0

Views: 155

Answers (2)

ControlAltDel
ControlAltDel

Reputation: 35106

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
    }

Upvotes: 1

rzwitserloot
rzwitserloot

Reputation: 103813

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
}

Upvotes: 0

Related Questions