Java 与InputStream或Reader的Files.readAllLines()等效?
我有一个文件,通过以下方法读取到列表中:Java 与InputStream或Reader的Files.readAllLines()等效?,java,jar,nio2,Java,Jar,Nio2,我有一个文件,通过以下方法读取到列表中: List<String> doc = java.nio.file.Files.readAllLines(new File("/path/to/src/resources/citylist.csv").toPath(), StandardCharsets.UTF_8); List doc=java.nio.file.Files.readAllLines(新文件(“/path/to/src/resources/citylist.csv”).to
List<String> doc = java.nio.file.Files.readAllLines(new File("/path/to/src/resources/citylist.csv").toPath(), StandardCharsets.UTF_8);
List doc=java.nio.file.Files.readAllLines(新文件(“/path/to/src/resources/citylist.csv”).toPath(),StandardCharsets.utf8);
有没有什么好的(单行)Java7/8/nio2方法可以让一个位于可执行Jar中的文件(可能必须用InputStream读取)完成同样的壮举?也许是一种通过类加载器打开InputStream的方法,然后以某种方式强制/转换/包装到Path对象中?或者InputStream或Reader的某个新子类,其中包含与File.readAllLines(…)等效的文件
我知道我可以用传统的方法在半页代码中完成,或者通过一些外部库。。。但在此之前,我想确保Java的最新版本不能“开箱即用”地完成这项工作。一个
输入流
表示一个字节流。这些字节不一定形成可以逐行读取的(文本)内容
try (InputStream resource = Example.class.getResourceAsStream("resource")) {
List<String> doc =
new BufferedReader(new InputStreamReader(resource,
StandardCharsets.UTF_8)).lines().collect(Collectors.toList());
}
如果您知道InputStream
可以解释为文本,则可以将其包装在InputStreamReader
中,并使用它逐行使用
try (InputStream resource = Example.class.getResourceAsStream("resource")) {
List<String> doc =
new BufferedReader(new InputStreamReader(resource,
StandardCharsets.UTF_8)).lines().collect(Collectors.toList());
}
try(InputStream资源=Example.class.getResourceAsStream(“资源”)){
清单文件=
新的BufferedReader(新的InputStreamReader)(资源、,
StandardCharsets.UTF_8)).lines().collect(collector.toList());
}
您可以使用Apache Commons:
List doc=IOUtils.readLines(inputStream,StandardCharsets.UTF_8)代码>为什么不(想)继续使用当前解决方案?当前解决方案只在应用程序在IntelliJ内部和我自己的计算机上运行时有效。这在今天仍然有效,但最终它必须能够从可执行文件运行。