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

Bit*_*g3r 39 java jar nio2

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

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

是否有任何好的(单行)Java 7/8/nio2方法可以使用可执行Jar内的文件(并且可能必须使用InputStream读取)来实现相同的功能?也许是通过类加载器打开InputStream的方法,然后以某种方式强制/转换/将其包装到Path对象中?或者是一些包含与File.readAllLines(...)等效的InputStream或Reader的新子类?

我知道我可以用半页代码中的传统方式,或者通过一些外部库来实现......但在此之前,我想确保最近发布的Java不能"开箱即用" ".

Sot*_*lis 57

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

如果您知道InputStream可以将其解释为文本,则可以将其包装在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());
}
Run Code Online (Sandbox Code Playgroud)


spl*_*tor 23

您可以使用Apache Commons IOUtils #readLines:

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