Unlike a character stream which reads data from a text file as strings, a binary stream needs to know exactly the type of data that is being read. In other words, if the data that it is reading is integer values it needs to be told to read integer values, if it is strings, it needs to know that it is strings that it should be reading, etc.
To read data from a binary file, you must use the following classes:
1.
FileInputStream
The FileInputStream class connects to a File object and creates an input stream that can read from the file.
The following table outlines the constructors for the FileInputStream class:
CONSTRUCTOR DESCRIPTION
FileInputStream(File f) Creates a file input stream from the specified File object.
Throws FileNotFoundException if the file doesn’t exist.
FileInputStream(String path) Creates a file input stream from the specified pathname.
Throws FileNotFoundException if the file doesn’t exist.
2.
BufferedInputStream
The BufferedInputStream class connects to a FileInputStream and adds input buffering.
CONSTRUCTOR DESCRIPTION
BufferedInputStream
(InputStream in)
Creates a buffered input stream from any object that extends the InputStream class. Typically you pass this constructor a FileInputStream object.
3.
DataInputStream
This is the class that you used to read data from the stream. This class knows how to read basic data types, including primitive types and strings.
CONSTRUCTOR DESCRIPTION
DataInputStream(InputStream in)
Creates a data output stream from the specified
InputStream object.
Reading Data from a Binary File Page 1 of 5
The following table outlines some of the methods included in the DataInputStream class:
METHODS DESCRIPTION boolean readBoolean() Reads a boolean value from the input stream. Throws
EOFException and IOException . char readChar() Reads a char value from the input stream. Throws
EOFException and IOException . double readDouble() int readInt()
Reads a double value from the input stream. Throws
EOFException and IOException .
Reads an int value from the input stream. Throws
EOFException and IOException . long readLong() Reads a long value from the input stream. Throws
EOFException and IOException .
String readUTF() Reads a string value from the input stream. Throws
EOFException and IOException . void close() Closes the input stream and releases any system resources associated with the stream. Throws IOException .
You can create a DataInputStream in one of two ways. The first method uses nested constructors to create each of the required objects:
File f = new File(“demo.dat”);
DataInputStream in = new DataInputStream(new
BufferedInputStream (new FileInputStream(f)));
Alternatively, you can create each object as a separate constructor as follows:
File f = new File(“demo.dat”);
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream in = new DataInputStream(bis);
Since the FileInputStream throws an exception if an error occurs, you will need to instantiate the
FileInputStream object within a try…catch statement as we did with the FileOutputStream class: import java.io.*; import javax.swing.*; public class Demo {
Reading Data from a Binary File Page 2 of 5
public static void main(String[] args) {
// Declare and initialize File object
File f = new File("test.dat"); try
{
// Declare and initialize DataOutputStream object
DataInputStream in = new DataInputStream(new
BufferedInputStream(new FileInputStream(f)));
} catch (IOException e)
{
// Output error message if file cannot be found
JOptionPane.showMessageDialog(null, “File not found!”,
“Error”, JOptionPane.ERROR_MESSAGE);
}
}
}
Unlike text files, which are read one line at a time and parsed into individual fields, reading binary files requires you to use the read() methods included in the DataInputStream class (see table above) which reads the fields one at a time. In order to this properly, you need to know the exact sequence in which data values appear in the file.
So, for example, if I were reading from a file that stores a name followed by an age, I would store the data in variables as follows:
String name = in.readUTF();
int age = in.readInt();
The read() methods are usually used in a while loop to read all the data from the file. When the end of the file is reached, an EOFException error is thrown. We can catch this exception and stop the loop as follows: boolean eof = false; while (!eof)
{ try
{
String name = in.readUTF();
int age = in.readInt();
} catch (EOFException e)
Reading Data from a Binary File Page 3 of 5
{
eof = true;
} catch (IOException e)
{
JOptionPane.showMessageDialog(null, “An IOExcpetion has occurred!”, “Error!”, JOptionPane.ERROR_MESSAGE);
}
}
The following example reads the names and ages from the binary file we created in the last lesson and outputs each name and age to the system console: import java.io.*; import javax.swing.*; public class ReadingBinaryFile { public static void main(String[] args) {
// Declare and intialize File object
File f = new File("info.dat");
try
{
// Declare and initialize DataInputStream object
DataInputStream in = new DataInputStream(new
BufferedInputStream(new FileInputStream(f)));
// Declare variable
boolean eof = false;
while (!eof)
{
try
{
// Read data from the file
String name = in.readUTF();
int age = in.readInt();
// Output data to the console
System.out.printf ("%-20s%-10d\n", name, age);
}
catch (EOFException e)
{
// Reached the end of the file
eof = true;
}
Reading Data from a Binary File Page 4 of 5
catch (IOException e)
{
// Catches the exception thrown by the read() methods
JOptionPane.showMessageDialog(null, "Cannot read data from file!", "Error!",
JOptionPane.ERROR_MESSAGE);
}
}
// Close DataInputStream object
in.close();
}
// Output error message if an exception is thrown
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e.getMessage() + "!",
"Error!", JOptionPane.ERROR_MESSAGE);
}
}
}
Reading Data from a Binary File Page 5 of 5