To read a file line by line we can make use of the static lines(Path path) method from the Files class from the java.nio.file package.
Let's take a look at an example.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
String filePath = "/Users/dev/Documents/Java-Projects/demo/src/data.txt";
try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
lines.forEach(System.out::println);
} catch (IOException e) {
System.out.println("Error occurred while reading the file!");
e.printStackTrace();
}
}
}

Note that lines() method was added to Files class in Java 8. It returns a Stream object using which we can iterate over the lines using the forEach() method.
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!