00:00

DataInputStream Class in Java: Reading Primitive Types

Last updated:

Saving an int or a double as text and parsing it back is slow and error-prone. Binary formats store numbers directly as bytes. DataInputStream reads those bytes back as Java primitive types such as int, long, double and boolean.

This tutorial covers the class, its reading methods and two examples, including the standard way to detect the end of the data.

1. What Is DataInputStream in Java?

DataInputStream is a filter stream that wraps another InputStream and implements the DataInput interface. It reads primitive values in a machine-independent format: the bytes written by a DataOutputStream on any platform are read back as the same values on any other platform.

2. DataInputStream Class Hierarchy

DataInputStream class hierarchyDataInputStream extends FilterInputStream, which extends InputStream and Object. It implements DataInput, Closeable and AutoCloseable. Each read method consumes a fixed number of bytes: readBoolean 1, readShort 2, readInt 4, readLong 8, readDouble 8, and readUTF a 2-byte length plus the string bytes.ObjectextendsInputStreamabstract classextendsFilterInputStreamwraps another InputStreamextendsDataInputStreamreads Java primitives from bytesDataInputCloseableAutoCloseableimplementsBytes consumedreadBoolean() 1readShort() 2readInt() 4readLong() 8readDouble() 8readUTF() 2 + n

Swipe sideways to see the whole diagram.

3. Constructor of DataInputStream

Constructor
public DataInputStream(InputStream in)

Wrap a buffered stream for files, for example new DataInputStream(new BufferedInputStream(Files.newInputStream(path))), because each method makes several small reads.

4. Methods for Reading Primitive Types

MethodReturnsBytes read
readBoolean()boolean1
readByte() / readUnsignedByte()byte / int (0–255)1
readShort() / readChar()short / char2
readInt() / readFloat()int / float4
readLong() / readDouble()long / double8
readUTF()String2-byte length, then the encoded text
readFully(byte[] b)voidExactly b.length
skipBytes(int n)intUp to n

If the stream ends before a value is complete, these methods throw EOFException.

5. Example: Loading a Saved Game

A game stores each save slot as a small binary file. Loading must read the values back in the same order and with the same types used for writing.

GameSaveLoader.java
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class GameSaveLoader {
    public static void main(String[] args) throws IOException {
        Path save = Files.createTempFile("slot1", ".sav");

        // Save the game (see DataOutputStream for details)
        try (DataOutputStream out = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(save)))) {
            out.writeUTF("Arjun");
            out.writeInt(7);           // level
            out.writeLong(1_250_000L); // score
            out.writeDouble(82.5);     // health
            out.writeBoolean(true);    // has the key
        }

        // Load it: read the values in exactly the same order and types
        try (DataInputStream in = new DataInputStream(new BufferedInputStream(Files.newInputStream(save)))) {
            String player = in.readUTF();
            int level = in.readInt();
            long score = in.readLong();
            double health = in.readDouble();
            boolean hasKey = in.readBoolean();
            System.out.println(player + " | level " + level + " | score " + score + " | health " + health + " | key " + hasKey);
        }
        Files.delete(save);
    }
}
Output
Arjun | level 7 | score 1250000 | health 82.5 | key true

How the code works

  1. DataOutputStream writes a string, an int, a long, a double and a boolean.
  2. DataInputStream calls the matching methods in the same order: readUTF(), readInt(), readLong(), readDouble(), readBoolean().
  3. Both streams are buffered, so the file is accessed in large blocks.

6. Example: Reading Records Until the End

A humidity sensor produces fixed-size records: the minute of the day (int) and a reading (float). The number of records is not stored, so the reader keeps going until the data ends.

SensorRecords.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;

public class SensorRecords {
    public static void main(String[] args) throws IOException {
        // Each record: minute of the day (int) + humidity in percent (float)
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (DataOutputStream out = new DataOutputStream(bytes)) {
            int[] minutes = {360, 420, 480};
            float[] humidity = {61.5f, 58.0f, 54.25f};
            for (int i = 0; i < minutes.length; i++) {
                out.writeInt(minutes[i]);
                out.writeFloat(humidity[i]);
            }
        }

        try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
            int records = 0;
            while (true) {
                try {
                    int minute = in.readInt();
                    float value = in.readFloat();
                    System.out.printf("%02d:%02d -> %.2f%%%n", minute / 60, minute % 60, value);
                    records++;
                } catch (EOFException end) {       // the normal way to detect the end
                    break;
                }
            }
            System.out.println("Records read: " + records);
        }
    }
}
Output
06:00 -> 61.50%
07:00 -> 58.00%
08:00 -> 54.25%
Records read: 3

How the code works

  1. Each record takes 8 bytes: 4 for the int and 4 for the float.
  2. Unlike read(), the typed methods cannot return -1, so they signal the end by throwing EOFException.
  3. Catching EOFException ends the loop after the third record.

7. Important Features

  • Multi-byte values are read in big-endian order (high byte first), the same order DataOutputStream writes.
  • readUTF() expects Java's modified UTF-8 with a 2-byte length prefix, as written by writeUTF().
  • The format stores no type information: the reader must know the exact layout.
  • Most read methods are final.

8. Common Mistakes and Best Practices

  • Reading in a different order or type. The bytes are misinterpreted; keep the read order identical to the write order.
  • Using readUTF() for ordinary text files. It only reads data written by writeUTF(); use a Reader for text.
  • Using the deprecated readLine(). It does not convert bytes to characters correctly; use BufferedReader.readLine().
  • Forgetting buffering. Wrap file streams in BufferedInputStream.

9. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.0DataInputStream and the DataInput interface.
Java 1.1readLine() deprecated in favour of BufferedReader.readLine().
Java 7Try-with-resources makes closing simple.
Java 25No API changes. For complex data, formats such as JSON or Protocol Buffers are often preferred.

10. Summary

  • DataInputStream reads Java primitives and modified UTF-8 strings from bytes.
  • It pairs with DataOutputStream; read in exactly the order you wrote.
  • Typed reads throw EOFException at the end of the data.
  • Wrap file streams in a buffer, and use readers, not readUTF(), for text files.

Related Tutorials

11. Official Java Documentation References