How to write to a binary file

Common methods of the DataOutput interface

Constructors Throws Description
writeBoolean(boolean) IOException Writes a 1-byte bollean value to the output stream.
writeInt(int) IOException Writes a 4-bytes value to the output stream.
writeDouble(double) IOException Writes an 8-bytes value to the output stream.
writeChar(int) IOException Writes 2-bytes char to the output stream.
writeChars(string) IOException Writes a string using 2 bytes per character to the output stream.
writeUTF(String) IOException Writes a string using 2 bytes value for the number of bytes in the string followed by the UTF representation of the string which typically uses 1 byte per character.

Method Throws Description
size() IOException Returns an int for the number of bytes written to the stream.
flush() IOException Flushes any data that's in the buffer to the file.
close() IOException Flushes any data that's in the buffer to the file and closes the stream.

Example 1: Code that writes data to a binary file

// write a Product object to the file
out.writeUTF(product.getCode());
out.writeUTF(product.getDescription());
out.writeUTF(product.getPrice());
// flush data to the file and close the output stream
in.close();

Description:

  • writeUTF mehtod uses the Universal Text Format (UTF)

More info can be found here: locate the location