Text file into Java List using Commons or

2019-04-19 03:37发布

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.

7条回答
疯言疯语
2楼-- · 2019-04-19 04:17

using org.apache.commons.io.FileUtils

FileUtils.readLines(new File("file.txt"));
查看更多
霸刀☆藐视天下
3楼-- · 2019-04-19 04:17

They are pretty similar, with Commons IO it will look like this:

List<String> lines = FileUtils.readLines(new File("file.txt"), "UTF-8");

Main advantage of Guava is the specification of the charset (no typos):

 List<String> lines = Files.readLines(new File("file.txt"), Charsets.UTF_8);
查看更多
女痞
4楼-- · 2019-04-19 04:17

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).

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.

查看更多
聊天终结者
5楼-- · 2019-04-19 04:21

Using Apache Commons IO, you can use FileUtils#readLines method. It is as simple as:

List<String> lines = FileUtils.readLines(new File("..."));
for (String line : lines) {
  System.out.println(line);  
}
查看更多
疯言疯语
6楼-- · 2019-04-19 04:23

This is probably what youre looking for

FileUtils.readLines(File file)

查看更多
Summer. ? 凉城
7楼-- · 2019-04-19 04:25

Here's how to do it with Guava:

List<String> lines = Files.readLines(new File("myfile.txt"), Charsets.UTF_8);

Reference:

查看更多
登录 后发表回答