Java MCQ: Which method is used to read a file using BufferedInputStream in Java?
Answer:
Explanation:
The read()
method in Java is used to read data from a file using the BufferedInputStream
class. BufferedInputStream
is part of the java.io
package and is used to read bytes from an input stream efficiently by buffering the input.
Here’s an example of how to use BufferedInputStream
to read data from a file:
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadFileBufferedInputStream {
public static void main(String[] args) {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("example.txt"))) {
int data;
while ((data = bis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
}
}
In this example, a BufferedInputStream
is created to wrap a FileInputStream
object. The read()
method is used in a loop to read one byte at a time from the file example.txt
. Each byte is cast to a char
and printed to the console. The loop continues until the read()
method returns -1
, indicating the end of the file.
The BufferedInputStream
class is used to increase the efficiency of input operations by buffering the bytes being read. This reduces the number of calls to the underlying input stream, improving performance, especially when reading large files.
The read()
method is fundamental for reading binary data or raw bytes from a file, making BufferedInputStream
an important tool for handling binary files or files where performance is critical.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html