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
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.