Problem: Write a Java program to read a text file line by line and output its contents.
To solve this problem, we will use the BufferedReader class in Java to read file line by line.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) {
// File path
String filePath = "path/to/file.txt";
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
// read each line in the file
while ((line = br.readLine()) != null) {
// print the line to the console
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Example.txt:
Output:
In this program, we have used BufferedReader
class to read a file line by line.
First, we specify the path for the text file, then, use it to create a FileReader
object.
We pass this object to the BufferedReader
constructor to enable buffered reading.
Notice, we are defining the BufferedReader
object within the try-with-resources
statement. This is to ensure that the BufferedReader
is closed properly, even if an exception is thrown.
We then use the while
loop to read lines from the file until readLine()
returns null
, the readLine()
method returns null
when the end of the file is reached.
Inside the while loop we read each line from the file and print it to the console using System.out.println()
statement.
Are there other ways to Read Files in Java?
Yes, there are various ways using which you can read files in Java. Here are a few examples:
FileInputStream
andDataInputStream
classes: These classes can be used to read binary data from a file.FileInputStream
reads raw bytes, whileDataInputStream
allows you to read Java-specific data types (such as int, double, etc.).Scanner
class: TheScanner
class can be used to read text data from a file (or other input sources) using a variety of delimiters. It also provides methods to read different data types (such as int, double, etc.).Files.readAllLines()
method (Java 7 and later): This method reads all the lines from a file and returns them in a List of Strings.Files.readString()
method (Java 11 and later): This method reads the entire content of a file as a String.Files.lines()
method (Java 8 and later): This method returns a Stream of Strings, where each element is a line from the file. This method allows you to perform operations such as filtering, mapping, and reducing on the lines of the file.
Each method has their own advantages, you can choose the one that fits your needs.