Reputation: 1189
I am trying to read text file whilst running the program from a jar archive. I come accros that I need to use InputStream to read file. The snippet of code:
buffer = new BufferedInputStream(this.getClass().getResourceAsStream((getClass().getClassLoader().getResource("English_names.txt").getPath())));
System.out.println(buffer.read()+" yeas");
At this line System.out.println(buffer.read()+" yeas");
program stops and nothing happens since then. Once you output the contents of buffer
object it is not null.
What might be the problem?
Upvotes: 0
Views: 2029
Reputation: 51
You should not worry about InputStream
being null
when passed into BufferedInputStream
constructor since it, the constructor handles null
parameters just fine. When supplied with null
it will just return null
without throwing any exception. Also since InputStream
implements AutoClosable
the try-with-resources
block will take care of closing your streams properly.
try (
final InputStream is = getClass().getResourceAsStream("/English_names.txt");
final BufferedInputStream bis = new BufferedInputStream(is);
) {
if (null == bis)
throw new IOException("requsted resource was not found");
// Do your reading.
// Do note that if you are using InputStream.read() you may want to call it in a loop until it returns -1
} catch (IOException ex) {
// Either resource is not found or other I/O error occurred
}
Upvotes: 0
Reputation: 77104
From InputStream#read()
:
This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
So basically, the stream appears to be waiting on content. I'm guessing it's how you've constructed the stream, you can simplify your construction to:
InputStream resourceStream = getClass().getResourceAsStream("/English_names.txt");
InputStream buffer = new BufferedInputStream(resourceStream);
I'd also check to make sure that resourceStream
is not-null.
Upvotes: 1