0

我正在尝试从 jar 存档运行程序时读取文本文件。我来了,我需要使用 InputStream 来读取文件。代码片段:

buffer = new BufferedInputStream(this.getClass().getResourceAsStream((getClass().getClassLoader().getResource("English_names.txt").getPath())));


System.out.println(buffer.read()+" yeas");

在这一行System.out.println(buffer.read()+" yeas");,程序停止,此后没有任何反应。一旦你输出buffer对象的内容,它就不是空的。可能是什么问题?

4

2 回答 2

1

来自InputStream#read()

此方法会一直阻塞,直到输入数据可用、检测到流结束或引发异常。

所以基本上,流似乎正在等待内容。我猜这是您构建流的方式,您可以将构建简化为:

InputStream resourceStream = getClass().getResourceAsStream("/English_names.txt");
InputStream buffer = new BufferedInputStream(resourceStream);

我还要检查以确保它resourceStream不为空。

于 2012-09-09T21:50:17.727 回答
0

你不应该担心InputStreamnull传递给BufferedInputStream构造函数时,构造null函数可以很好地处理参数。当提供它时,null它只会返回null而不抛出任何异常。此外,由于InputStream实现AutoClosable了该try-with-resources块将负责正确关闭您的流。

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 
    }
于 2018-03-12T13:08:19.430 回答