00:00

DataOutputStream Class in Java: Writing Primitive Types

Last updated:

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

DataOutputStream class hierarchyDataOutputStream extends FilterOutputStream, which extends OutputStream and Object. It implements DataOutput, Closeable, Flushable and AutoCloseable. Each write method produces a fixed number of bytes: writeBoolean 1, writeShort 2, writeInt 4, writeLong 8, writeDouble 8, and writeUTF a 2-byte length plus the string bytes.ObjectextendsOutputStreamabstract classextendsFilterOutputStreamwraps another OutputStreamextendsDataOutputStreamwrites Java primitives as bytesDataOutputCloseableFlushableAutoCloseableimplementsBytes writtenwriteBoolean() 1writeShort() 2writeInt() 4writeLong() 8writeDouble() 8writeUTF() 2 + n

Swipe sideways to see the whole diagram.

3. Constructor of DataOutputStream

Constructor
public DataOutputStream(OutputStream out)

For files, wrap a buffered stream: new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(path))).

4. Methods for Writing Primitive Types

MethodWritesBytes
writeBoolean(boolean v)1 for true, 0 for false1
writeByte(int v)The low 8 bits1
writeShort(int v) / writeChar(int v)Two bytes, high byte first2
writeInt(int v) / writeFloat(float v)Four bytes, high byte first4
writeLong(long v) / writeDouble(double v)Eight bytes, high byte first8
writeUTF(String s)2-byte length, then modified UTF-82 + encoded length
writeChars(String s)Each char as two bytes2 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.

GameSaveWriter.java
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);
    }
}
Output
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

  1. writeUTF("Arjun") writes a 2-byte length plus 5 bytes of text: 7 bytes.
  2. writeInt adds 4 bytes, writeLong and writeDouble add 8 each, and writeBoolean adds 1, for 28 bytes in total.
  3. 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.

ByteOrderDemo.java
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")));
    }
}
Output
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

  1. writeInt(0x12345678) produces 12 34 56 78: the high byte comes first (big-endian).
  2. writeShort(500) produces 01 f4, because 500 is 0x01F4.
  3. writeUTF("Hi") writes the length 00 02 and then 48 69, while writeChars("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 throw UTFDataFormatException.

9. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.0DataOutputStream and the DataOutput interface.
Java 7Try-with-resources makes closing simple.
Java 17HexFormat, used in the example, makes it easy to inspect written bytes.
Java 25No API changes; the binary format is unchanged and stable.

10. Summary

  • DataOutputStream writes Java primitives and strings as compact, portable bytes.
  • Each type uses a fixed size: 1 byte for boolean, 4 for int, 8 for long and double.
  • Values are written big-endian; writeUTF() adds a 2-byte length.
  • Read the data back with DataInputStream in exactly the same order.

Related Tutorials

11. Official Java Documentation References