O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Binary Data

Problem

You need to read or write binary data, as opposed to text.

Solution

Use a DataInputStream or DataOutputStream.

Discussion

The Stream classes have been in Java since the JDK 1.0 release and are optimal for reading/writing bytes, rather than characters. The “data” layer over them, comprising DataInputStream and DataOutputStream, are configured for reading and writing binary values, including all of Java’s built-in types. Suppose that you want to write a binary integer plus a binary floating-point value into a file and read it back later. This code shows the writing part:

import java.io.*;
/** Write some data in binary. */
public class WriteBinary {
    public static void main(String argv[]) throws IOException {
        int i = 42;
        double d = Math.PI;
        String FILENAME = "binary.dat";
        DataOutputStream os = new DataOutputStream(
            new FileOutputStream(FILENAME));
        os.writeInt(i);
        os.writeDouble(d);
        os.close(  );
        System.out.println("Wrote " + i + ", " + d + " to file " + FILENAME);
    }
}

The reading part is left as an exercise for the reader. Should you need to write all the fields from an object, you should probably use an ObjectDataStream ; see Section 9.17.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required