使用 Commons 或 Guava 将文本文件转换为 Java List<String>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4580322/
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
Text file into Java List<String> using Commons or Guava
提问by Mat B.
What is the most elegant way to put each line of text (from the text file) into LinkedList (as String object) or some other collection, using Commons or Guava libraries.
使用 Commons 或 Guava 库将每行文本(来自文本文件)放入 LinkedList(作为 String 对象)或其他一些集合的最优雅的方法是什么。
回答by Sean Patrick Floyd
回答by Jo?o Silva
Using Apache Commons IO, you can use FileUtils#readLines
method. It is as simple as:
使用Apache Commons IO,您可以使用FileUtils#readLines
方法。这很简单:
List<String> lines = FileUtils.readLines(new File("..."));
for (String line : lines) {
System.out.println(line);
}
回答by Wouter Coekaerts
You can use Guava:
您可以使用番石榴:
Files.readLines(new File("myfile.txt"), Charsets.UTF_8);
Or apache commons io:
或 apache 公共 io:
FileUtils.readLines(new File("myfile.txt"));
I'd say both are equally elegant.
我想说两者都同样优雅。
Depending on your exact use, assuming the "default encoding" might be a good idea or not. Either way, personally I find it good that the Guava API makes it clear that you're making an assumption about the encoding of the file.
根据您的确切用途,假设“默认编码”可能是一个好主意,也可能不是。无论哪种方式,我个人都觉得 Guava API 清楚地表明您正在对文件的编码做出假设是好的。
Update: Java 7 now has this built in: Files.readAllLines(Path path, Charset cs). And there too you have to specify the charset explicitly.
更新:Java 7 现在内置了:Files.readAllLines(Path path, Charset cs)。而且您还必须明确指定字符集。
回答by Paul
using org.apache.commons.io.FileUtils
使用 org.apache.commons.io.FileUtils
FileUtils.readLines(new File("file.txt"));
回答by John Vint
回答by Fabian Steeg
They are pretty similar, with Commons IO it will look like this:
它们非常相似,对于 Commons IO,它看起来像这样:
List<String> lines = FileUtils.readLines(new File("file.txt"), "UTF-8");
Main advantage of Guava is the specification of the charset (no typos):
Guava 的主要优点是字符集的规范(没有错别字):
List<String> lines = Files.readLines(new File("file.txt"), Charsets.UTF_8);
回答by zpon
I'm not sure if you only want to know how to do this via Guava or Commons IO, but since Java 7 this can be done via java.nio.file.Files.readAllLines(Path path, Charset cs)
(javadoc).
我不确定您是否只想知道如何通过 Guava 或 Commons IO 执行此操作,但是由于 Java 7,这可以通过java.nio.file.Files.readAllLines(Path path, Charset cs)
( javadoc) 完成。
List<String> allLines = Files.readAllLines(dir.toPath(), StandardCharsets.UTF_8);
Since this is part of the Java SE it does not require you to add any additional jar files (Guava or Commons) to your project.
由于这是 Java SE 的一部分,因此不需要您向项目添加任何额外的 jar 文件(Guava 或 Commons)。