In this tutorial, you will learn how to read a file as list of strings in Java, using readAllLines() method of java.nio.file.Files class.
Java – Read file as List of strings
To read a file as List of strings in Java,
- Given a file path, create a Path object, say filePath.
- Pass the filePath as argument to the readAllLines() method of java.nio.file.Files class.
- readAllLines() method returns the content in the file as a List<String> object. Store this List<String> object in a variable, say lines.
- Now, you may use a Java For loop to iterate each of the line in this lines object.
1. Read the file “data.txt” as List of strings in Java
In the following program, we take a file path "/Users/tutorialkart/data.txt"
, read the content of this file as List of strings, and print the lines to standard output.
In the program,
- Given a file path filePath as String.
String filePath = "/Users/tutorialkart/data.txt";
- Create an instance of Path object path with the given filePath.
Path path = Paths.get(filePath);
- Call Files.readAllLines() method and pass the path object as argument to it. The method returns the lines in the file as a List of strings. Store the list in a variable lines.
List<String> lines = Files.readAllLines(path);
- Use a For loop to iterate over the List of strings, lines.
for (int i=0; i < lines.size(); i++) { System.out.println("Line " + (i+1) + " : " + lines.get(i)); }
The following is the complete Java program, to read the file as List of strings, and print the lines to output.
Java Program
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class Main { public static void main(String[] args) { String filePath = "/Users/tutorialkart/data.txt"; try { // Prepare file path object Path path = Paths.get(filePath); // Read lines in file as a list of strings List<String> lines = Files.readAllLines(path); // Iterate over lines, and print to output for (int i=0; i < lines.size(); i++) { System.out.println("Line " + (i+1) + " : " + lines.get(i)); } } catch (IOException e) { e.printStackTrace(); } } }
Output
Line 1 : Apple is red. Line 2 : Banana is yellow. Line 3 : Cherry is red.
ADVERTISEMENT
Conclusion
In this Java File Operations tutorial, we learned how to read the file as List of strings using java.nio.file.Files.readAllLines() method, with examples.