Skip to lesson

Simple binary formats with data streams

A text file stores the number 1234567 as seven digit characters. A binary format stores it as the 4 bytes Java uses in memory, which is smaller, faster to read and exact, but no longer readable in Notepad.

DataOutputStream: writeInt, writeDouble and writeUTF

DataOutputStream wraps an OutputStream and writes Java values as a fixed number of bytes: writeInt 4 bytes, writeLong 8, writeDouble 8, writeBoolean 1. writeUTF writes a String as a 2-byte length followed by the text in a slightly changed form of UTF-8.

Example 1 · What writeInt, writeUTF and writeDouble put on disk

DataWriteDemo.javaJava
import java.io.BufferedOutputStream;import java.io.DataOutputStream;import java.io.FileOutputStream;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class DataWriteDemo {    public static void main(String[] args) throws IOException {        Path dir = Files.createTempDirectory("data");        Path file = dir.resolve("student.dat");        try (DataOutputStream out = new DataOutputStream(                new BufferedOutputStream(new FileOutputStream(file.toFile())))) {            out.writeInt(101);        // roll number: 4 bytes            out.writeUTF("Asha");     // name: 2-byte length + 4 bytes            out.writeDouble(8.7);     // CGPA: 8 bytes        }
        byte[] bytes = Files.readAllBytes(file);        System.out.println("File size: " + bytes.length + " bytes");        StringBuilder hex = new StringBuilder();        for (int i = 0; i < bytes.length; i++) {            hex.append(String.format("%02X", bytes[i]));            hex.append(i == 3 || i == 9 ? " | " : " ");        }        System.out.println(hex.toString().trim());        Files.delete(file);        Files.delete(dir);    }}
Output
File size: 18 bytes
00 00 00 65 | 00 04 41 73 68 61 | 40 21 66 66 66 66 66 66

What this code does

  • 101 is 65 in hex, written as 4 bytes with the most significant first. Asha is the length 00 04 and then the letters A, s, h, a (41 73 68 61).
  • The last 8 bytes are the double 8.7 exactly as Java stores it in memory. Nothing in the file says which part is which; only the order of the calls does.

The bytes always go most significant byte first (called big-endian), on every computer. So a file written on Windows reads back the same on a Mac. For files, put a buffer in the chain: new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))). Each writeInt would otherwise make several tiny writes.

writeUTF can store at most 65,535 bytes of text; longer strings throw UTFDataFormatException.

Reading back in the same order

DataInputStream has a matching read method for each write: readInt, readDouble, readUTF, readBoolean and so on. The file holds no names, labels or separators, only the bytes of the values one after another.

Example 2 · Save a list with a count, load it in the same order

SaveLoadDemo.javaJava
import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;
record Student(int roll, String name, double cgpa) {}
public class SaveLoadDemo {    static void save(Path file, List<Student> students) throws IOException {        try (DataOutputStream out = new DataOutputStream(                new BufferedOutputStream(new FileOutputStream(file.toFile())))) {            out.writeInt(students.size());            for (Student s : students) {                out.writeInt(s.roll());                out.writeUTF(s.name());                out.writeDouble(s.cgpa());            }        }    }
    static List<Student> load(Path file) throws IOException {        List<Student> result = new ArrayList<>();        try (DataInputStream in = new DataInputStream(                new BufferedInputStream(new FileInputStream(file.toFile())))) {            int count = in.readInt();            for (int i = 0; i < count; i++) {                int roll = in.readInt();                String name = in.readUTF();                double cgpa = in.readDouble();                result.add(new Student(roll, name, cgpa));            }        }        return result;    }
    public static void main(String[] args) throws IOException {        Path dir = Files.createTempDirectory("students");        Path file = dir.resolve("students.dat");        save(file, List.of(new Student(101, "Asha", 8.7),                           new Student(102, "Ravi", 7.25),                           new Student(103, "Meenakshi", 9.1)));        System.out.println("Saved " + Files.size(file) + " bytes");        for (Student s : load(file)) {            System.out.println(s);        }        Files.delete(file);        Files.delete(dir);    }}
Output
Saved 63 bytes
Student[roll=101, name=Asha, cgpa=8.7]
Student[roll=102, name=Ravi, cgpa=7.25]
Student[roll=103, name=Meenakshi, cgpa=9.1]

What this code does

  • save writes the count first and then, for every student, an int, a String and a double. load reads the count and calls readInt, readUTF and readDouble in the same order.
  • The doubles come back exactly, with no rounding, because their 8 bytes were stored as they are in memory. The file is 63 bytes: 4 for the count, 18 each for Asha and Ravi (4 + 6 + 8) and 23 for Meenakshi (4 + 11 + 8).

Example 3 · Bug: reading in a different order

WrongOrderDemo.javaJava
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 WrongOrderDemo {    public static void main(String[] args) throws IOException {        ByteArrayOutputStream bytes = new ByteArrayOutputStream();        try (DataOutputStream out = new DataOutputStream(bytes)) {            out.writeInt(101);   // roll            out.writeInt(87);    // marks        }
        try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {            long wrong = in.readLong();          // the reader expects one long            System.out.println("readLong gave " + wrong);            try {                in.readInt();            } catch (EOFException e) {                System.out.println("Next readInt: EOFException, nothing left");            }        }
        try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {            System.out.println("Right order: roll " + in.readInt() + ", marks " + in.readInt());        }    }}
Output
readLong gave 433791696983
Next readInt: EOFException, nothing left
Right order: roll 101, marks 87

What this code does

  • readLong took all 8 bytes of the two ints and joined them: 101 × 2³² + 87. No exception warned about the mistake; the number is simply wrong.
  • Because the long used up every byte, the next read hit the end. Reading two ints, in the same order as the writer, gives the right values.

So the reader must call the read methods in exactly the same order and with the same types as the writer. Read an int where a double was written, and you get a wrong number with no error at all. The usual way to save a list is to write the number of items first, then each item's fields. The reader reads the count and loops that many times.

EOFException at the end

When there are no more bytes, readInt, readUTF and the other read methods throw EOFException (end of file), a subclass of IOException. They cannot return -1 like read(), because -1 is a perfectly valid int value.

Example 4 · Reading until EOFException, and spotting a cut file

ReadToEndDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.EOFException;import java.io.IOException;import java.util.Arrays;
public class ReadToEndDemo {    static void readAll(String label, byte[] data) throws IOException {        int records = 0;        try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(data))) {            while (true) {                String name;                try {                    name = in.readUTF();            // first field: EOF here is a clean end                } catch (EOFException end) {                    System.out.println(label + ": " + records + " records, clean end");                    return;                }                try {                    int runs = in.readInt();                    records++;                    System.out.println("  " + name + " scored " + runs);                } catch (EOFException cut) {                    System.out.println(label + ": " + records + " records, then the file ended inside a record");                    return;                }            }        }    }
    public static void main(String[] args) throws IOException {        ByteArrayOutputStream bytes = new ByteArrayOutputStream();        try (DataOutputStream out = new DataOutputStream(bytes)) {            out.writeUTF("Rohit");            out.writeInt(74);            out.writeUTF("Virat");            out.writeInt(103);            out.writeUTF("Shubman");            out.writeInt(52);        }        byte[] full = bytes.toByteArray();        readAll("Full file", full);        readAll("Cut file", Arrays.copyOf(full, full.length - 2));    }}
Output
  Rohit scored 74
  Virat scored 103
  Shubman scored 52
Full file: 3 records, clean end
  Rohit scored 74
  Virat scored 103
Cut file: 2 records, then the file ended inside a record

What this code does

  • The loop has no count to go by, so it reads until EOFException. An exception on the name means no record was started: a normal end.
  • The cut file loses the last 2 bytes, so readInt for Shubman's runs hits the end in the middle of a record. Telling the two cases apart lets the program report a damaged file instead of quietly losing data.

If you did not write a count, read in a loop and stop when EOFException arrives. Read the first field of each record on its own: an EOFException there means a clean end, while one in the middle of a record means the file is cut short. A count at the start is still the cleaner design, because the reader knows when to stop without relying on an exception.

Binary versus text formats: size and readability

A binary format stores values as raw bytes; a text format such as CSV stores them as readable characters. Each wins in different places.

Example 5 · The same numbers as binary and as text

BinaryVsTextDemo.javaJava
import java.io.ByteArrayOutputStream;import java.io.DataOutputStream;import java.io.IOException;import java.nio.charset.StandardCharsets;
public class BinaryVsTextDemo {    public static void main(String[] args) throws IOException {        int[] fees = { 7, 82, 100, 45000, 1234567 };        double[] values = { 8.7, Math.PI };
        ByteArrayOutputStream binary = new ByteArrayOutputStream();        StringBuilder text = new StringBuilder();        try (DataOutputStream out = new DataOutputStream(binary)) {            for (int f : fees) {                out.writeInt(f);                text.append(f).append('\n');            }            for (double v : values) {                out.writeDouble(v);                text.append(v).append('\n');            }        }        int textBytes = text.toString().getBytes(StandardCharsets.UTF_8).length;        System.out.println("Binary: " + binary.size() + " bytes");        System.out.println("Text:   " + textBytes + " bytes");        System.out.print("Text you can read:\n" + text);    }}
Output
Binary: 36 bytes
Text:   45 bytes
Text you can read:
7
82
100
45000
1234567
8.7
3.141592653589793

What this code does

  • Every int takes 4 bytes in binary, so 7 costs more than its 2 text bytes, while 1234567 costs less than its 8. Each double is always 8 bytes; π needs 18 bytes as text.
  • The text version is bigger here, but anyone can read and fix it. The binary version is only meaningful to code that knows the exact order of ints and doubles.
  • Size: binary uses 4 bytes for any int; text uses one byte per digit plus a separator, so big numbers cost more as text and small ones less.
  • Exactness: writeDouble keeps every bit of a double; text keeps only the digits you print.
  • Readability: you can open, check and fix a text file in any editor; a binary file needs your program.
  • Sharing: CSV and JSON work with spreadsheets and other languages; a home-made binary format works only with code that knows its exact layout.

Next step

Check your understanding

12 quick questions