The contents of a binary file are a sequence of primitive type values (bytes, characters, short integers, integers, long integers, floats, doubles or booleans) or UTF encoded strings. There are no "lines" in a binary file … it is just a sequence of binary values of the types mentioned above.
A binary file is not "human readable".
Create a file by instantiating an instance of the FileOutputStream class. Then create a new DataOutputStream object to write to that file. DataOutputStream objects have output methods the correspond to the different primitive types and UTF-8 encoded strings. The names of these methods are writeByte(), writeInt(), writeDouble(), writeUTF(), etc.
FileOutputStream f = new FileOutputStream("binary_output.dat");
DataOutputStream dos = new DataOutputStream(f);
// now use dos.writeInt(int i), dos.writeDouble(double d), dos.writeUTF(String s), (…) etc.
Open the binary file by creating an instance of the FileInputStream class. Then create a new instance of the DataInputStream class to read from that input stream. The DataInputStream object has methods to read values of each of the primitive types and UTF encoded strings. The method names include readBoolean(), readDouble(), readUTF(), etc.
You can write and values of primitive types and UTF encoded strings to a binary file. It is conceivable that you could write a String to a binary file by using the writeChar() method to output one character at a time. You would probably want to precede this by an integer value specifying the length of the string. This procedure would have to be reversed to read the string back into another program. This is, in effect, what the writeUTF() method does for you when you use it to write a string to a binary file.
The higher level readInt(), readDouble(), readUTF(), etc methods of DataInputStream objects will all throw an EOFException if end of file is encountered during execution of an input request. In order to continue processing, your program will have to catch that exception and handle it (perhaps by simply closing the file, or even by doing nothing).
The more primitive read() methods of the DataInputStream class, which read one unsigned byte at a time from the input stream, will return a value of -1 if they encounter end of file, so you can just watch for that return value. You are unlikely, however, to want to use these primitive methods to read a binary file.
| Things to try |
|---|
|
© Wiggen & Associates, 2007