Aphex
Aphex

Reputation: 408

ObjectInputStream and Binary Data

I got problems loading my application up with a binary file. I am trying to read from the binary file and inject the data to some HashMaps/ArrayLists in my application.

public void loadBinary(String filename) {
    InputStream input = getClass().getResourceAsStream(filename);
    try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(input))) {

         // TODO

    } catch (IOException | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}

It points to the rather long line

try (ObjectInputStream in ... ) {

to be where it throws an exception.

Exception in thread "main" java.lang.RuntimeException: java.io.IOException: Stream closed

How they I "open" the stream/fix this issue? Thanks!

EDIT:

More of the error

Caused by: java.io.IOException: Stream closed
at java.io.BufferedInputStream.getInIfOpen(BufferedInputStream.java:159)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
at java.io.ObjectInputStream$PeekInputStream.read(ObjectInputStream.java:2313)
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2326)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2797)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:802)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at model.Model.loadBinary(Model.java:245)
... 7 more

Upvotes: 1

Views: 537

Answers (2)

user207421
user207421

Reputation: 311048

From BufferedInputStream.getInIfOpen() [Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.][quoted under fair-use]:

private InputStream getInIfOpen() throws IOException {
    InputStream input = in;
    if (input == null)
        throw new IOException("Stream closed");
        return input;
    }

Very strange code. It should throw a NullPointerException. Possibly it is overloading null to also indicate closure, which is poor practice.

In any case that's the cause of your problem. The resource wasn't found, so input was null. You should have checked for that before creating the ObjectInputStream.

Upvotes: 2

Aphex
Aphex

Reputation: 408

I solved it now. The problem was very silly, nonetheless an issue.

When I gave the method the binary as a file, the path should be "folder/sub-folder/file.bin", but as an InputStream it should just read "/sub-folder/file.bin".

Can anyone elaborate why its structured like this?

Upvotes: 0

Related Questions