Reading a File in Java using DataInputStream

In Java, if you're looking to read primitive data types (like int, float, double, boolean, etc.) in a machine-independent way, DataInputStream is the class you turn to. Especially when working with binary data formats, this stream plays an integral role. In this article, we'll explore how to read files using DataInputStream

1. Understanding DataInputStream 

DataInputStream is part of the package and allows you to read Java primitives from an input stream in a machine-independent manner. This is especially useful when reading data written by a DataOutputStream. 

2. Reading a File Using DataInputStream 

To illustrate, let's assume you have a binary file that contains an int, a boolean, and a UTF string, written in that order by DataOutputStream. Here's how you can read the file:


public class DataInputStreamDemo {
    public static void main(String[] args) {
        String filePath = "sample.bin";

        try (DataInputStream dis = new DataInputStream(new FileInputStream(filePath))) {
            int intValue = dis.readInt();
            boolean boolValue = dis.readBoolean();
            String stringValue = dis.readUTF();

            System.out.println("Int Value: " + intValue);
            System.out.println("Boolean Value: " + boolValue);
            System.out.println("String Value: " + stringValue);
        } catch (IOException e) {
            System.out.println("Error reading the file: " + e.getMessage());

In this example: 

We've wrapped a FileInputStream instance inside a DataInputStream

We then use the appropriate methods (readInt(), readBoolean(), and readUTF()) to read the data types.

3. Advantages of Using DataInputStream 

Consistency: With DataInputStream, you can reliably read data across different platforms. The data read would be consistent, irrespective of the machine it was written on or is being read on. 

Simplicity: The class provides straightforward methods to read various primitive data types. 

4. Points to Remember 

Data Order: Ensure you read data in the same sequence as it was written. If you try to read data in a different sequence, you might get unexpected results or runtime exceptions. 

EOFException: If you try to read past the end of the file, a will be thrown. Ensure you handle this exception if the exact file size is unknown. 

5. Conclusion 

DataInputStream is a powerful class in Java's I/O library, especially when you need to read primitive data types in a standardized, machine-independent manner. By coupling it with the appropriate output stream (DataOutputStream), you can effectively manage binary data storage and retrieval tasks in your applications.