In Java 11 and later, you can use the Files.lines
method of the java.nio.file.Files
class to read a file line by line.
To use the Files.lines
method to read a file line by line, you can use the following syntax:
try (Stream<String> stream = Files.lines(Paths.get("file.txt"))) { stream.forEach(System.out::println); } catch (IOException e) { // handle I/O exception }
Here, file.txt
is the name of the file to be read, and stream
is a Stream
of String
objects representing the lines of the file.
The Files.lines
method returns a Stream
of String
objects that can be processed using the Stream
API.
In this example, the forEach
terminal operation is used to iterate over the lines of the file and print them to the console.
It is important to note that the Files.lines
method reads the file lazily, which means that the file is not read until the Stream
is consumed.
This allows you to process the lines of the file efficiently and consume only the lines that you need.
It is also important to note that the Files.lines
method throws an IOException
if an I/O error occurs while reading the file.
Therefore, it is recommended to use the try-with-resources
statement to ensure that the Stream
is closed properly, and to catch any IOException
that may be thrown.
Alternatively, you can use the BufferedReader
class to read a file line by line, like this:
String filepath = "test.txt"; File fp = new File(filepath); FileReader fr = new FileReader(fp); BufferedReader br = new BufferedReader(fr); ArrayList<String> lines = new ArrayList<>(); String line; while ((line = br.readLine()) != null) { lines.add(line); } fr.close(); System.out.println("lines:" + lines);