简体   繁体   中英

Reading file from by InputStream object

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?

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.

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 
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM