Text file into Java List using Commons or

2019-04-19 04:12发布

问题:

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.

回答1:

Here's how to do it with Guava:

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

Reference:

  • Files.readLines(File, Charset)


回答2:

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);  
}


回答3:

You can use Guava:

Files.readLines(new File("myfile.txt"), Charsets.UTF_8);

Or apache commons 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.

Update: Java 7 now has this built in: Files.readAllLines(Path path, Charset cs). And there too you have to specify the charset explicitly.



回答4:

using org.apache.commons.io.FileUtils

FileUtils.readLines(new File("file.txt"));


回答5:

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


回答6:

This is probably what youre looking for

FileUtils.readLines(File file)



回答7:

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.