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:
- 284,665
- 62
- 456
- 576
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);
}
- 85,475
- 27
- 147
- 152
-
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.
- 8,845
- 3
- 29
- 35
using org.apache.commons.io.FileUtils
FileUtils.readLines(new File("file.txt"));
- 4,686
- 3
- 28
- 38
This is probably what youre looking for
- 284,665
- 62
- 456
- 576
- 38,644
- 6
- 74
- 105
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,009
- 7
- 83
- 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,414
- 1
- 15
- 21