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: FileOutputStream(File f) FileOutputStream(File f, boolean append) FileOutputStream(String path) Creates a file writer from the file. Throws 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. Creates a file writer from the specified pathname. Throws Writing Data to a Binary File Page 1 of 5
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 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. 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. 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 void close() void flush() int size() void writeboolean(boolean value) void writechar(char value) void writedouble(double value) void writeint(int value) Closes the file. Writes the contents of the buffer to disk. Returns the number of bytes written to the file. Writes a boolean value to the output stream. Throws Writes a char value to the output stream. Throws Writes a double value to the output stream. Throws Writes an int value to the output stream. Throws Writing Data to a Binary File Page 2 of 5
void writelong(long value) void writeutf(string value) Writes a long value to the output stream. Throws 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 ); 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 catch (IOException e) // Output error message if exception is thrown JOptionPane.showMessageDialog(null, e.getmessage() +!, Error, JOptionPane.ERROR_MESSAGE); Writing Data to a Binary File Page 3 of 5
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 // 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); Writing Data to a Binary File Page 4 of 5
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: Writing Data to a Binary File Page 5 of 5