DataInputStream Class in Java: Reading Primitive Types
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
Swipe sideways to see the whole diagram.
3. Constructor of DataInputStream
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
| Method | Returns | Bytes read |
|---|---|---|
readBoolean() | boolean | 1 |
readByte() / readUnsignedByte() | byte / int (0–255) | 1 |
readShort() / readChar() | short / char | 2 |
readInt() / readFloat() | int / float | 4 |
readLong() / readDouble() | long / double | 8 |
readUTF() | String | 2-byte length, then the encoded text |
readFully(byte[] b) | void | Exactly b.length |
skipBytes(int n) | int | Up 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.
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);
}
}
Arjun | level 7 | score 1250000 | health 82.5 | key true
How the code works
DataOutputStreamwrites a string, anint, along, adoubleand aboolean.DataInputStreamcalls the matching methods in the same order:readUTF(),readInt(),readLong(),readDouble(),readBoolean().- 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.
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);
}
}
}
06:00 -> 61.50% 07:00 -> 58.00% 08:00 -> 54.25% Records read: 3
How the code works
- Each record takes 8 bytes: 4 for the
intand 4 for thefloat. - Unlike
read(), the typed methods cannot return-1, so they signal the end by throwingEOFException. - Catching
EOFExceptionends the loop after the third record.
7. Important Features
- Multi-byte values are read in big-endian order (high byte first), the same order
DataOutputStreamwrites. readUTF()expects Java's modified UTF-8 with a 2-byte length prefix, as written bywriteUTF().- 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 bywriteUTF(); use aReaderfor text. - Using the deprecated
readLine(). It does not convert bytes to characters correctly; useBufferedReader.readLine(). - Forgetting buffering. Wrap file streams in
BufferedInputStream.
9. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.0 | DataInputStream and the DataInput interface. |
| Java 1.1 | readLine() deprecated in favour of BufferedReader.readLine(). |
| Java 7 | Try-with-resources makes closing simple. |
| Java 25 | No API changes. For complex data, formats such as JSON or Protocol Buffers are often preferred. |
10. Summary
DataInputStreamreads Java primitives and modified UTF-8 strings from bytes.- It pairs with
DataOutputStream; read in exactly the order you wrote. - Typed reads throw
EOFExceptionat the end of the data. - Wrap file streams in a buffer, and use readers, not
readUTF(), for text files.