CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Files

Text and Binary Files
Binary files
Read from a binary file

Common methods of the DataInput interface

Method Throws Description
readBoolean() EOFException Reads 1 byte and returns a boolean value.
readInt() EOFException Reads 4 bytes and returns an int value.
readDouble() EOFException Reads 8 bytes and returns a double value.
readChar() EOFException Reads 2 bytes and returns a char value.
readUTF() EOFException Reads and returns the string encoded with UTF.
skipBytes(int) EOFException Tries to skip the specified number of bytes, and returns an int value for the actual number skipped.

Common methods of the DataInputStream class

Method Throws Description
available() IOException Returns the number of bytes remaining in the file.
close() IOException Closes the stream.

CAUTION: You have to read the data in the same order and same format in which they are stored. For example, since names are written in UTF-8 using writeUTF, you must read names using readUTF.

TIP: If you keep reading data at the end of a stream, an EOFException would occur. So how do you check the end of a file? You can use input.available() to check it.

input.available() == 0 indicates that it is the end of a file.

Code that reads a Product object from a binary file

// read product data from a 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();
Previous | Binary I/O | Connect a binary output stream to a file | Write to a binary file | Connect a binary input stream to a file | Read from a binary file | Two ways with binary strings | Next