问题描述
我有一个文件,我通过以下方法读入List:
I have a file that I've been reading into a List via the following method:
List<String> doc = java.nio.file.Files.readAllLines(new File("/path/to/src/resources/citylist.csv").toPath(), StandardCharsets.UTF_8);
是否有任何好的(单行)Java 7/8 / nio2方法来实现相同的目标使用可执行Jar内的文件(并且可能必须使用InputStream读取)?也许是一种通过类加载器打开InputStream的方法,然后以某种方式强制/转换/将其包装到Path对象中?或者InputStream或Reader的一些新子类,它包含与File.readAllLines(...)等价的内容?
Is there any nice (single-line) Java 7/8/nio2 way to pull off the same feat with a file that's inside an executable Jar (and presumably, has to be read with an InputStream)? Perhaps a way to open an InputStream via the classloader, then somehow coerce/transform/wrap it into a Path object? Or some new subclass of InputStream or Reader that contains an equivalent to File.readAllLines(...)?
我知道我可以这样做半页代码中的传统方式,或者通过一些外部库...但在此之前,我想确保最近发布的Java不能开箱即用。
I know I could do it the traditional way in a half page of code, or via some external library... but before I do, I want to make sure that recent releases of Java can't already do it "out of the box".
推荐答案
InputStream
表示字节流。这些字节不一定形成(文本)内容,可以逐行读取。
An InputStream
represents a stream of bytes. Those bytes don't necessarily form (text) content that can be read line by line.
如果您知道 InputStream
可以解释为文本,您可以将其包装在 InputStreamReader
中并使用逐行使用它。
If you know that the InputStream
can be interpreted as text, you can wrap it in a InputStreamReader
and use BufferedReader#lines()
to consume it line by line.
try (InputStream resource = Example.class.getResourceAsStream("resource")) {
List<String> doc =
new BufferedReader(new InputStreamReader(resource,
StandardCharsets.UTF_8)).lines().collect(Collectors.toList());
}
这篇关于相当于InputStream或Reader的Files.readAllLines()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!