Java MCQ: Which class is used to read data from a file using DataInputStream in Java?
Answer:
Explanation:
The DataInputStream
class in Java is used to read primitive data types from an input stream in a machine-independent way. It is part of the java.io
package and is typically used in conjunction with a FileInputStream
to read data from files.
Here’s an example of how to use DataInputStream
to read data from a file:
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadFileDataInputStream {
public static void main(String[] args) {
try (DataInputStream dis = new DataInputStream(new FileInputStream("example.dat"))) {
int data = dis.readInt();
System.out.println("Read integer: " + data);
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
}
}
In this example, a DataInputStream
is created to wrap a FileInputStream
object. The readInt()
method is used to read an integer from the file example.dat
. The integer is then printed to the console. The DataInputStream
class provides methods like readInt()
, readDouble()
, readUTF()
, and others to read different types of data from a file.
DataInputStream
is particularly useful when you need to read data that was written using a DataOutputStream
, ensuring that the data is read in the correct format and is platform-independent.
This class is essential for reading structured binary data from files, such as when working with custom file formats or data that includes a mix of primitive types.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html