Recipe 10.15 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 and writing bytes rather than characters. The "data" layer over them, comprising DataInputStream and DataOutputStream, is 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 one of the methods described in Recipe 10.18.



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net