• No results found

WRITING DATA TO A BINARY FILE

N/A
N/A
Protected

Academic year: 2021

Share "WRITING DATA TO A BINARY FILE"

Copied!
5
0
0

Loading.... (view fulltext now)

Full text

(1)

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.

(2)

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.

(3)

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);

}

(4)

}

}

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);

}

(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:

References

Related documents

Echo hiding is a method of hiding secret message in audio signal, with the binary format without much Start Read MP3 file Read text file Convert separated file to

• Section 5, Binary Process Control , which describes how to create binary control solutions using the Process Object and Signal Object libraries.. • Section 6, Synchronized Control

The Trade File – Derivatives Market (Non-SOM) (Binary Format) includes 3 types of information – (1) Derivatives Reference data, (2) Derivatives Trade and (3)

The reason is that in this scheme, if the file system is not compromised when the class key for a class of files is created, and that class key is copied, encrypted with

File organization refers to the way yield is stored in a file File organization is writing important whether it determines the methods of access efficiency flexibility and

Fabasoft Folio Upload Application 7 The file is uploaded and an object of the object class combined with the file extension of the file is created. The object is displayed in the

Each file is a linked list of disk blocks, scattered anywhere on the disk. At file creation time, simply tell the directory about the file. When writing, get a

Seasoned technology professional with node excel file example of the existing cells lose their use synchronous writing file information from my binary classifier to comment one