DataOutputStream Class in Java: Writing Primitive Types
When an application stores numbers, flags and short strings in a compact binary file, writing them as text wastes space and needs parsing later. DataOutputStream writes Java primitive values directly as bytes, in a format that any Java program can read back with DataInputStream.
This tutorial covers the class, its write methods, how many bytes each one produces and the exact byte layout.
1. What Is DataOutputStream in Java?
DataOutputStream is a filter stream that wraps another OutputStream and implements the DataOutput interface. It converts primitives such as int, long and double into a fixed number of bytes, in a machine-independent order. It has been part of Java since version 1.0.
2. DataOutputStream Class Hierarchy
Swipe sideways to see the whole diagram.
3. Constructor of DataOutputStream
public DataOutputStream(OutputStream out)
For files, wrap a buffered stream: new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(path))).
4. Methods for Writing Primitive Types
| Method | Writes | Bytes |
|---|---|---|
writeBoolean(boolean v) | 1 for true, 0 for false | 1 |
writeByte(int v) | The low 8 bits | 1 |
writeShort(int v) / writeChar(int v) | Two bytes, high byte first | 2 |
writeInt(int v) / writeFloat(float v) | Four bytes, high byte first | 4 |
writeLong(long v) / writeDouble(double v) | Eight bytes, high byte first | 8 |
writeUTF(String s) | 2-byte length, then modified UTF-8 | 2 + encoded length |
writeChars(String s) | Each char as two bytes | 2 per char |
size() | Returns the number of bytes written so far | – |
5. Example: Saving a Game and Measuring Its Size
A game saves the player name, level, score, health and whether the player has found a key. size() shows how the file grows with each value.
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class GameSaveWriter {
public static void main(String[] args) throws IOException {
Path save = Files.createTempFile("slot1", ".sav");
try (DataOutputStream out = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(save)))) {
out.writeUTF("Arjun");
System.out.println("After writeUTF(\"Arjun\"): " + out.size() + " bytes");
out.writeInt(7);
System.out.println("After writeInt(7): " + out.size() + " bytes");
out.writeLong(1_250_000L);
System.out.println("After writeLong(...): " + out.size() + " bytes");
out.writeDouble(82.5);
System.out.println("After writeDouble(82.5): " + out.size() + " bytes");
out.writeBoolean(true);
System.out.println("After writeBoolean(true): " + out.size() + " bytes");
}
System.out.println("File size: " + Files.size(save) + " bytes");
Files.delete(save);
}
}
After writeUTF("Arjun"): 7 bytes
After writeInt(7): 11 bytes
After writeLong(...): 19 bytes
After writeDouble(82.5): 27 bytes
After writeBoolean(true): 28 bytes
File size: 28 bytes
How the code works
writeUTF("Arjun")writes a 2-byte length plus 5 bytes of text: 7 bytes.writeIntadds 4 bytes,writeLongandwriteDoubleadd 8 each, andwriteBooleanadds 1, for 28 bytes in total.- The file contains exactly those 28 bytes and can be read back with
DataInputStream.
6. Example: Seeing the Exact Bytes
To see the format, this program writes values into memory and prints the bytes in hexadecimal.
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.HexFormat;
public class ByteOrderDemo {
static String hexOf(BytesWriter writer) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (DataOutputStream out = new DataOutputStream(bytes)) {
writer.write(out);
}
return HexFormat.ofDelimiter(" ").formatHex(bytes.toByteArray());
}
interface BytesWriter {
void write(DataOutputStream out) throws IOException;
}
public static void main(String[] args) throws IOException {
System.out.println("writeInt(0x12345678): " + hexOf(out -> out.writeInt(0x12345678)));
System.out.println("writeShort(500): " + hexOf(out -> out.writeShort(500)));
System.out.println("writeUTF(\"Hi\"): " + hexOf(out -> out.writeUTF("Hi")));
System.out.println("writeChars(\"Hi\"): " + hexOf(out -> out.writeChars("Hi")));
}
}
writeInt(0x12345678): 12 34 56 78
writeShort(500): 01 f4
writeUTF("Hi"): 00 02 48 69
writeChars("Hi"): 00 48 00 69
How the code works
writeInt(0x12345678)produces12 34 56 78: the high byte comes first (big-endian).writeShort(500)produces01 f4, because 500 is 0x01F4.writeUTF("Hi")writes the length00 02and then48 69, whilewriteChars("Hi")writes two bytes per character.
7. Important Features
- All multi-byte values are written big-endian, so files are portable between platforms.
writeUTF()uses modified UTF-8 and is limited to 65,535 encoded bytes per string.- No type information or field names are stored; reader and writer must agree on the layout.
- Most write methods are
final.
8. Common Mistakes and Best Practices
- Using
writeBytes(String)for text. It keeps only the low byte of each character, losing non-ASCII characters. - Changing the layout without versioning. Write a version number first so old files can still be read.
- Forgetting to close or flush. With a buffered stream underneath, unflushed bytes are lost.
- Writing very long strings with
writeUTF(). Strings over the limit throwUTFDataFormatException.
9. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.0 | DataOutputStream and the DataOutput interface. |
| Java 7 | Try-with-resources makes closing simple. |
| Java 17 | HexFormat, used in the example, makes it easy to inspect written bytes. |
| Java 25 | No API changes; the binary format is unchanged and stable. |
10. Summary
DataOutputStreamwrites Java primitives and strings as compact, portable bytes.- Each type uses a fixed size: 1 byte for
boolean, 4 forint, 8 forlonganddouble. - Values are written big-endian;
writeUTF()adds a 2-byte length. - Read the data back with
DataInputStreamin exactly the same order.
Related Tutorials
- DataInputStream Class in Java
- BufferedOutputStream Class in Java
- ByteArrayOutputStream Class in Java