How to read from a binary file

Common methods of the DataInput interface

Constructors Throws Description
readBoolean(boolean) IOException Reads 1-byte bollean value to the output stream.
readInt(int) IOException Reads 4-bytes value to the output stream.
readDouble(double) IOException Reads 8-bytes value to the output stream.
readChar(int) IOException Reads 2-bytes char to the output stream.
readUTF(string) IOException Reads and returns the string encoded with UTF.
skipbytes(int) IOException Attempts to skip the specified number of bytes, and returns an int value for the actual number of bytes skipped.

Method Throws Description
available() IOException Returns an int for the number of bytes written to the stream.
close() IOException Closes the stream.

Example 1: Code that reads a Product object from a binar file

// read a Product object to the file
String code = in.readUTF();
String description = in.readUTF();
double price = in.readDouble();
// create the Product object from its data
Product p = new Product(code, description, price);
// close the input stream
in.close();

Description:

  • The readUTF method reads characters that were written with the Universal Text Format.

More info can be found here: locate the location