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 Answers
Here's how to do it with Guava:
List<String> lines = Files.readLines(new File("myfile.txt"), Charsets.UTF_8);
Reference:

- 292,901
- 67
- 465
- 588
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);
}

- 89,303
- 29
- 152
- 158
-
2`IOUtils.lineIterator` is a better choice as it doesn't load the entire file into memory. – Steve Kuo Apr 06 '14 at 03:55
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.

- 9,395
- 3
- 31
- 35
using org.apache.commons.io.FileUtils
FileUtils.readLines(new File("file.txt"));

- 4,812
- 3
- 27
- 38
This is probably what youre looking for

- 292,901
- 67
- 465
- 588

- 39,695
- 7
- 78
- 108
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);

- 44,988
- 7
- 85
- 112
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.

- 1,482
- 1
- 15
- 21