Java 相当于 InputStream 或 Reader 的 Files.readAllLines()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29282457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:43:54  来源:igfitidea点击:

equivalent to Files.readAllLines() for InputStream or Reader?

javajarnio2

提问by Bitbang3r

I have a file that I've been reading into a List via the following method:

我有一个文件,我一直在通过以下方法读入 List:

List<String> doc = java.nio.file.Files.readAllLines(new File("/path/to/src/resources/citylist.csv").toPath(), StandardCharsets.UTF_8);

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 7/8/nio2 方法可以使用可执行 Jar 中的文件(大概必须使用 InputStream 读取)来实现相同的功能?也许是一种通过类加载器打开 InputStream 的方法,然后以某种方式将其强制/转换/包装到 Path 对象中?或者包含等效于 File.readAllLines(...) 的 InputStream 或 Reader 的一些新子类?

I know I coulddo 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".

我知道我可以在半页代码中以传统方式或通过一些外部库做到这一点……但在我这样做之前,我想确保最近发布的 Java 还不能“开箱即用” ”。

采纳答案by Sotirios Delimanolis

An InputStreamrepresents a stream of bytes. Those bytes don't necessarily form (text) content that can be read line by line.

AnInputStream表示字节流。这些字节不一定形成可以逐行读取的(文本)内容。

If you know that the InputStreamcan be interpreted as text, you can wrap it in a InputStreamReaderand use BufferedReader#lines()to consume it line by line.

如果您知道InputStream可以将the解释为文本,则可以将其包装在 a 中InputStreamReader并用于BufferedReader#lines()逐行使用它。

try (InputStream resource = Example.class.getResourceAsStream("resource")) {
  List<String> doc =
      new BufferedReader(new InputStreamReader(resource,
          StandardCharsets.UTF_8)).lines().collect(Collectors.toList());
}

回答by splintor

You can use Apache Commons IOUtils#readLines:

您可以使用 Apache Commons IOUtils#readLines

List<String> doc = IOUtils.readLines(inputStream, StandardCharsets.UTF_8);

List<String> doc = IOUtils.readLines(inputStream, StandardCharsets.UTF_8);