Java DataInput and DataOutput: Reading and Writing Binary Data
Write and read binary data in Java with DataOutputStream and DataInputStream: fixed-size big-endian numbers, readFully and EOFException, unsigned reads, why writeUTF's modified UTF-8 isn't real UTF-8, portable length-prefixed strings, and handling little-endian data with ByteBuffer.
kvi5hnuCode Sprout team member8 min readOn this page
Text files are easy to read and debug, but they're bulky and slow to parse: the number 1234567 takes seven characters, plus a separator, and must be converted from digits on every read. Binary formats store values the way the machine handles them, with a fixed number of bytes per value. The DataOutput and DataInput interfaces and their implementations DataOutputStream and DataInputStream are Java's basic tools for that.
Writing binary data
DataOutput has a write method for every primitive type, plus two for strings:
| Method | Bytes written |
|---|---|
writeBoolean(boolean) | 1 (0 or 1) |
writeByte(int) | 1 |
writeShort(int), writeChar(int) | 2 |
writeInt(int), writeFloat(float) | 4 |
writeLong(long), writeDouble(double) | 8 |
writeChars(String) | 2 per char (UTF-16), no length |
writeUTF(String) | 2-byte length, then "modified UTF-8" |
writeInt(1234) always writes exactly four bytes, 00 00 04 D2, however many digits the number has, and writeDouble always writes eight. That fixed size is what makes binary formats fast to read and lets you compute where a value sits in a file (next article).
To write to a file, wrap a DataOutputStream around a file stream, with a buffer in between for speed (article 19):
var out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("employee.dat")));
out.writeInt(1234);
out.writeDouble(75000.0);
Byte order
How should the four bytes of an int be ordered? Big-endian puts the most significant byte first: 1234 = 0x000004D2 is stored as 00 00 04 D2. Little-endian starts with the least significant byte: D2 04 00 00. Processors differ. x86-64 and most ARM systems are little-endian, while network protocols and many older RISC processors use big-endian. A C program that dumps memory to a file writes the processor's native order, which makes the file awkward to move between platforms.
Java's data streams always use big-endian, regardless of the processor, so their files are portable between Java programs everywhere. If you must read little-endian data written by another program, read the bytes into a ByteBuffer and set its order (article 30):
int value = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt();
Alternatively, Integer.reverseBytes, Long.reverseBytes and Short.reverseBytes swap the order of a value you've already read.
Reading binary data
DataInput has the matching read methods: readBoolean, readByte, readShort, readChar, readInt, readLong, readFloat, readDouble and readUTF. There are also some extras:
readUnsignedByte()andreadUnsignedShort()return the value as a non-negativeint. Java'sbyteis signed, so the byteFFis -1 as abytebut 255 unsigned. Binary formats often use unsigned fields.readFully(byte[] b)reads exactlyb.lengthbytes, blocking until they've all arrived. UnlikeInputStream.read(byte[]), it never returns early.skipBytes(n)tries to skipnbytes and returns the number actually skipped.
Read the values in exactly the same order and with the same types as they were written. A binary file carries no labels. If you write an int and read a long, you silently get garbage.
If the input ends in the middle of a value, the read methods throw an EOFException, a subclass of IOException. That's different from InputStream.read(), which returns -1. Sometimes code uses EOFException to detect the end of a file of records, but it's cleaner to write a record count first, or to compare the position with the file length.
Strings in binary files
Strings have no fixed size, so they need care.
writeChars writes each char as two bytes, but it doesn't record the length, so a reader can't tell where the string ends. You must store the length separately or use fixed-size fields as in the next article. There's no matching readChars method.
writeUTF writes a two-byte length followed by the characters in modified UTF-8. That's not the standard UTF-8 that everybody else uses. It differs in two ways:
- A character outside the Basic Multilingual Plane, such as an emoji, is first split into its UTF-16 surrogate pair, and each surrogate is encoded separately as three bytes, giving six bytes instead of the standard four. 😀 becomes
ED A0 BD ED B8 80instead ofF0 9F 98 80. - The NUL character U+0000 is written as two bytes
C0 80instead of a single00, so the encoded string never contains a zero byte.
This format dates from the days before Unicode outgrew 16 bits. It's what the JVM uses for strings inside class files, and it's what Java serialization uses. Because of the two-byte length, writeUTF also can't handle strings that encode to more than 65,535 bytes: it throws a UTFDataFormatException.
For your own binary formats, use standard UTF-8 with a length prefix. It's portable to any language and has no size limit:
static void writeString(DataOutput out, String s) throws IOException {
byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
out.writeInt(bytes.length);
out.write(bytes);
}
static String readString(DataInput in) throws IOException {
var bytes = new byte[in.readInt()];
in.readFully(bytes);
return new String(bytes, StandardCharsets.UTF_8);
}
A complete example
import java.io.*;
import java.nio.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class Solution {
static String hex(byte[] bytes) {
return HexFormat.ofDelimiter(" ").withUpperCase().formatHex(bytes);
}
static byte[] bytesOf(DataWriter writer) throws IOException {
var bout = new ByteArrayOutputStream();
try (var out = new DataOutputStream(bout)) {
writer.write(out);
}
return bout.toByteArray();
}
interface DataWriter {
void write(DataOutput out) throws IOException;
}
// portable strings: a length followed by standard UTF-8 bytes
static void writeString(DataOutput out, String s) throws IOException {
byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
out.writeInt(bytes.length);
out.write(bytes);
}
static String readString(DataInput in) throws IOException {
var bytes = new byte[in.readInt()];
in.readFully(bytes);
return new String(bytes, StandardCharsets.UTF_8);
}
public static void main(String[] args) throws IOException {
// fixed sizes, big-endian
System.out.println("writeInt(1234): " + hex(bytesOf(out -> out.writeInt(1234))));
System.out.println("writeShort(-2): " + hex(bytesOf(out -> out.writeShort(-2))));
System.out.println("writeLong(1): " + hex(bytesOf(out -> out.writeLong(1))));
System.out.println("writeDouble(1.0): " + hex(bytesOf(out -> out.writeDouble(1.0))));
System.out.println("writeBoolean(true): " + hex(bytesOf(out -> out.writeBoolean(true))));
System.out.println("writeChar('é'): " + hex(bytesOf(out -> out.writeChar('é'))));
System.out.println("writeChars(\"Hi\"): " + hex(bytesOf(out -> out.writeChars("Hi"))));
// writeUTF: a two-byte length, then modified UTF-8
System.out.println("writeUTF(\"José\"): " + hex(bytesOf(out -> out.writeUTF("José"))));
System.out.println("😀 with writeUTF: " + hex(bytesOf(out -> out.writeUTF("😀"))));
System.out.println("😀 in real UTF-8: " + hex("😀".getBytes(StandardCharsets.UTF_8)));
System.out.println("NUL with writeUTF: " + hex(bytesOf(out -> out.writeUTF("\0"))));
try {
bytesOf(out -> out.writeUTF("x".repeat(70_000)));
} catch (UTFDataFormatException e) {
System.out.println("writeUTF of 70,000 chars: UTFDataFormatException");
}
// a round trip through a byte array
byte[] record = bytesOf(out -> {
out.writeInt(42);
out.writeDouble(Math.E);
writeString(out, "Grüße 😀");
out.writeBoolean(false);
});
System.out.println("record is " + record.length + " bytes");
try (var in = new DataInputStream(new ByteArrayInputStream(record))) {
System.out.println("read: " + in.readInt() + ", " + in.readDouble() + ", "
+ readString(in) + ", " + in.readBoolean());
in.readInt();
} catch (EOFException e) {
System.out.println("reading past the end: EOFException");
}
// little-endian data from other programs: use a ByteBuffer
byte[] littleEndian = { (byte) 0xD2, 0x04, 0x00, 0x00 };
int wrong = new DataInputStream(new ByteArrayInputStream(littleEndian)).readInt();
int right = ByteBuffer.wrap(littleEndian).order(ByteOrder.LITTLE_ENDIAN).getInt();
System.out.println("D2 04 00 00 as big-endian: " + wrong + ", as little-endian: " + right);
System.out.println("Integer.reverseBytes(" + wrong + ") = " + Integer.reverseBytes(wrong));
// unsigned values
try (var in = new DataInputStream(new ByteArrayInputStream(new byte[] { (byte) 0xFF, (byte) 0xFF }))) {
in.mark(2);
System.out.println("0xFF as readByte: " + in.readByte() + ", as readUnsignedByte: " + in.readUnsignedByte());
in.reset();
System.out.println("0xFFFF as readUnsignedShort: " + in.readUnsignedShort());
}
}
}
writeInt(1234): 00 00 04 D2
writeShort(-2): FF FE
writeLong(1): 00 00 00 00 00 00 00 01
writeDouble(1.0): 3F F0 00 00 00 00 00 00
writeBoolean(true): 01
writeChar('é'): 00 E9
writeChars("Hi"): 00 48 00 69
writeUTF("José"): 00 05 4A 6F 73 C3 A9
😀 with writeUTF: 00 06 ED A0 BD ED B8 80
😀 in real UTF-8: F0 9F 98 80
NUL with writeUTF: 00 02 C0 80
writeUTF of 70,000 chars: UTFDataFormatException
record is 29 bytes
read: 42, 2.718281828459045, Grüße 😀, false
reading past the end: EOFException
D2 04 00 00 as big-endian: -771489792, as little-endian: 1234
Integer.reverseBytes(-771489792) = 1234
0xFF as readByte: -1, as readUnsignedByte: 255
0xFFFF as readUnsignedShort: 65535
Look at the hex dumps: writeShort(-2) gives FF FE (two's complement), writeDouble(1.0) gives the IEEE 754 bit pattern 3F F0 ..., and writeUTF puts the byte count 00 05 before José.
Common questions
Is DataOutputStream the same as serialization?
No. Data streams write only the primitive values you ask for, with no type information. Object streams (article 32) are built on top of them and also write class descriptions and object graphs. Data streams are simpler, faster and language-neutral; serialization is Java-specific.
How do I write or read an unsigned 32-bit value?
Java has no unsigned int. Write the value with writeInt and read it back with Integer.toUnsignedLong(in.readInt()), which gives the value 0 to 4,294,967,295 as a long. Integer.toUnsignedString, Integer.divideUnsigned and Integer.compareUnsigned handle the rest.
How do I read the header of a known binary format, such as a PNG file?
Read the fixed fields in order with readFully and the read methods, checking the "magic number" first. A PNG file starts with the eight bytes 89 50 4E 47 0D 0A 1A 0A, followed by chunks with a big-endian length, a 4-byte type and the data, which matches DataInputStream's byte order.
What is the default byte order of a ByteBuffer?
Big-endian, like the data streams, whatever the processor uses. Call order(ByteOrder.LITTLE_ENDIAN) for little-endian data, and ByteOrder.nativeOrder() tells you the processor's order.
Why is my binary file not readable by a C program?
Common reasons are byte order (Java writes big-endian, C dumps native order, usually little-endian), writeUTF's modified UTF-8 and length prefix, and padding: a C struct may contain alignment gaps that Java does not write. Define the format byte by byte and implement it on both sides.
API reference
java.io.DataOutput (implemented by DataOutputStream and RandomAccessFile)
| Method | Description |
|---|---|
void writeBoolean(boolean b), writeByte(int b), writeShort(int s), writeChar(int c), writeInt(int i), writeLong(long l), writeFloat(float f), writeDouble(double d) | write a value in big-endian binary form |
void write(byte[] b), write(byte[] b, int off, int len) | write raw bytes |
void writeChars(String s) | writes each char as two bytes, without a length |
void writeUTF(String s) | writes a two-byte length and the string in modified UTF-8 |
java.io.DataInput (implemented by DataInputStream and RandomAccessFile)
| Method | Description |
|---|---|
boolean readBoolean(), byte readByte(), short readShort(), char readChar(), int readInt(), long readLong(), float readFloat(), double readDouble() | read a value; EOFException if the input ends first |
int readUnsignedByte(), int readUnsignedShort() | read an unsigned value as an int |
void readFully(byte[] b), readFully(byte[] b, int off, int len) | read exactly the requested number of bytes |
int skipBytes(int n) | skips up to n bytes; returns the number skipped |
String readUTF() | reads a string written by writeUTF |
java.lang.Integer (similar in Short and Long)
| Method | Description |
|---|---|
static int reverseBytes(int i) | swaps the byte order, converting between big- and little-endian |
Summary
DataOutputStreamandDataInputStreamwrite and read primitive values in a fixed number of bytes, which is compact and fast.- Java always uses big-endian byte order. For little-endian data, use a
ByteBufferwithByteOrder.LITTLE_ENDIANorreverseBytes. - Read values in exactly the order and types they were written. Running out of input throws
EOFException. readUnsignedByteandreadUnsignedShorthandle unsigned fields.readFullyreads an exact number of bytes.writeUTFuses modified UTF-8 with a 64 KB limit, which is meant for Java-internal use. For your own formats, write a length followed by standard UTF-8 bytes.
Practice Questions
Which bytes does out.writeInt(258) produce?
00 00 01 02. 258 = 0x102, and Java writes the four bytes in big-endian order, most significant first.
A C program on an x86 machine wrote an int that your DataInputStream reads as 16777216. What was the original value, and how do you read it correctly?
16777216 is 0x01000000, so the bytes were 01 00 00 00, which is 1 in little-endian order. Use Integer.reverseBytes(value), or read the bytes into a ByteBuffer with order(ByteOrder.LITTLE_ENDIAN).
Why shouldn't you use writeUTF for a file that a Python program will read?
writeUTF writes modified UTF-8, which encodes emoji and other supplementary characters as six bytes and NUL as C0 80. A standard UTF-8 decoder rejects or misreads those sequences. Write a length followed by getBytes(StandardCharsets.UTF_8) instead.
What's the difference between InputStream.read(byte[] b) and DataInput.readFully(byte[] b)?
read may return after reading fewer bytes than b.length and returns -1 at the end. readFully keeps reading until the array is full and throws EOFException if the input ends first.
A binary file stores a "flags" field as one byte with value 200. readByte() returns -56. Why, and how do you get 200?
byte is signed in Java, with range -128 to 127, so the bit pattern of 200 reads as -56. Use readUnsignedByte(), or readByte() & 0xFF.
Previous: Java Character Encodings: UTF-8, Charsets and the Default Encoding
Related reading
- Java Character Encodings: UTF-8, Charsets and the Default Encoding
- Java Text Input and Output: PrintWriter, BufferedReader and Saving Objects as Text
- Java I/O Filters: Buffered, Data and Pushback Streams
- Java I/O Streams: Reading and Writing Bytes
- Java Parallel Streams: When They Help, Ordering and Thread Safety

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.