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.
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.
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.
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)
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With