Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text file into Java List<String> using Commons or Guava

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.

like image 762
MatBanik Avatar asked Jan 02 '11 20:01

MatBanik


People also ask

How to read whole text file as String in Java?

The readString() method of File Class in Java is used to read contents to the specified file. Return Value: This method returns the content of the file in String format. Note: File. readString() method was introduced in Java 11 and this method is used to read a file's content into String.

How to read All text from file in Java?

To read all the bytes from a file, we can use the readAllBytes() method, which takes the path to the file and returns a byte array containing the bytes read from the file. To get output in the string format, pass the byte array to the String constructor with a charset for decoding.


2 Answers

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)
like image 140
Sean Patrick Floyd Avatar answered Sep 19 '22 18:09

Sean Patrick Floyd


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);  
}
like image 36
João Silva Avatar answered Sep 20 '22 18:09

João Silva