WRITING DATA TO A BINARY FILE
TEXT FILES VS. BINARY FILES
Up to now, we have looked at how to write and read characters to and from a text file. Text files are files that contain sequences of characters. Binary files, on the other hand, are files that contain sequences of binary digits.
Unlike text files which are designed to be read by human beings, binary files are designed to be read by programs.
The following are just some of the advantages of using binary files versus text files:
One of the biggest advantages of using binary files over text files is that they are more efficient to process than text files. Unlike a text file whose characters need to be converted into binary, a binary file is already in stored in a format that the computer understands.
A binary file is much smaller than a text file that contains an equivalent amount of data.
Some kinds of data cannot be easily represented as characters (e.g. the bytecode of a Java class file or the code stored in an executable file).
THE CLASSES USED TO WRITE TO A BINARY FILE
To write data to a binary file, you must use the following classes:
1. FileOutputStream
The FileOutputStream class connects to a File object and creates an output stream that can write to the file. However, this output stream can only write raw bytes to the file; it doesn’t know how to write Integer, Double, or String values.
The following table outlines the constructors for the FileOutputStream class:
CONSTRUCTOR DESCRIPTION
FileOutputStream(File f) Creates a file writer from the file. Throws FileNotFoundException if an error occurs.
FileOutputStream(File f, boolean
append) Creates a file writer from the file. If the second parameter is true, data is added to the end of the file if the file already exists. Throws FileNotFoundException if an error occurs.
FileOutputStream(String path) Creates a file writer from the specified pathname. Throws FileNotFoundException if an error occurs.
FileOutputStream(String path, boolean append)
Creates a file writer from the specified pathname. If the second parameter is true, data is added to the end of the file if the file already exists. Throws
FileNotFoundException if an error occurs.
2. BufferedOutputStream
The BufferedOutputStream class connects to a FileOutputStream and adds output buffering.
Without the buffer, in other words, data is written one character at a time. This class lets the program accumulate data in a buffer and writes the data only when the buffer is filled up or when the program requests that the data be written.
CONSTRUCTOR DESCRIPTION
BufferedOutputStream
(OutputStream out) Creates a buffered output stream for the specified stream.
Typically you pass this constructor a FileOutputStream object.
3. DataOutputStream
This class adds the ability to write primitive data types and strings to a stream.
CONSTRUCTOR DESCRIPTION
DataOutputStream
(OutputStream out) Creates a data output stream for the specified output stream.
The following table outlines some of the methods included in the DataOutputStream class:
METHODS DESCRIPTION
void close() Closes the file.
void flush() Writes the contents of the buffer to disk.
int size() Returns the number of bytes written to the file.
void writeBoolean(boolean value) Writes a boolean value to the output stream. Throws IOException error.
void writeChar(char value) Writes a char value to the output stream. Throws IOException error.
void writeDouble(double value) Writes a double value to the output stream. Throws IOException error.
void writeInt(int value) Writes an int value to the output stream. Throws IOException error.
void writeLong(long value) Writes a long value to the output stream. Throws IOException error.
void writeUTF(String value) Writes a string stored in UTF format to the output stream.
Throws EOFException, IOException, and UTFDataFormatException errors.
CREATING A DataOutputStream OBJECT
You can create a DataOutputStream in one of two ways. The first method uses nested constructors to create each of the required objects:
File f = new File(“demo.dat”);
DataOutputStream out = new DataOutputStream(new
BufferedOutputStream(new FileOutputStream(f)));
Alternatively, you can create each object as a separate constructor as follows:
File f = new File(“demo.dat”);
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
DataOutputStream out = new DataOutputStream(bos);
Since the FileOutputStream throws an exception if an error occurs, you will need to instantiate the FileOutputStream object within a try…catch statement as we did with the FileWriter class:
import java.io.*;
import javax.swing.*;
public class Demo {
public static void main(String[] args) {
// Declare and initialize File object
File f = new File("test.dat");
try
{
// Declare and initialize DataOutputStream object
DataOutputStream out = new DataOutputStream(new
BufferedOutputStream(new FileOutputStream(f)));
}
catch (IOException e)
{
// Output error message if exception is thrown
JOptionPane.showMessageDialog(null, e.getMessage() + “!”,
“Error”, JOptionPane.ERROR_MESSAGE);
}
}
}
WRITING TO A BINARY STREAM
Once you have successfully created a DataOutputStream object, writing data to a binary file is simply a matter of calling the various methods included in the DataOutputStream class to write different data types to the file. The following example prompts the user for his/her name and age and writes the data to a file called info.dat:
import java.io.*;
import javax.swing.*;
public class Demo {
public static void main(String[] args) {
// Declare and intialize File object
File f = new File("info.dat");
try
{
// Declare and initialize DataOutputStream object
DataOutputStream out = new DataOutputStream(new
BufferedOutputStream(new FileOutputStream(f)));
// Prompt user for name and age
String name = JOptionPane.showInputDialog(null, "Please
enter your name:", "Binary File Demo",
JOptionPane.INFORMATION_MESSAGE);
int age = Integer.parseInt(JOptionPane.showInputDialog
(null, "Please enter your age:", "Binary File Demo",
JOptionPane.INFORMATION_MESSAGE));
// Write data to file
out.writeUTF(name);
out.writeInt(age);
// Close DataOutputStream object
out.close();
}
catch (IOException e)
{
// Output error message if exception is thrown
JOptionPane.showMessageDialog(null, e.getMessage() + "!",
"Error!", JOptionPane.ERROR_MESSAGE);
}
}
}
If the user enters Jack Black as his name and age 40, this is what the binary file would look like when opened in Notepad: