Java MCQ: Which method is used to read a file using BufferedReader in Java?
Answer:
Explanation:
The readLine()
method in Java is used to read a file line by line using the BufferedReader
class. BufferedReader
is part of the java.io
package and is used to read text from an input stream efficiently by buffering the characters.
Here’s an example of how to use BufferedReader
to read a file line by line:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileBufferedReader {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
}
}
In this example, a BufferedReader
is created to wrap a FileReader
object. The readLine()
method is then used in a loop to read each line from the file example.txt
. The method returns null
when the end of the file is reached, which breaks the loop. Each line is printed to the console.
The BufferedReader
class is commonly used for reading text files because it provides an efficient way to read characters, arrays, and lines from a file. It is particularly useful when dealing with large files, as it minimizes the number of I/O operations by buffering the input.
Overall, readLine()
is a crucial method for reading files in Java, allowing developers to process text files line by line easily.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html