The readLine() method returns null when it has reached the end of a file.
In Java, the readLine()
method is typically associated with reading data from a BufferedReader
or a similar class that reads characters from a stream. When readLine()
reaches the end of a file, it returns null
.
Here’s a simple example using BufferedReader
:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
String fileName = "example.txt";
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, the readLine()
method is used in a while
loop to read lines from the file until it reaches the end. When the end of the file is reached, readLine()
returns null
, and the loop terminates.