SlideShare a Scribd company logo
1 of 151
BINARY I/O
Objectives
CHAPTER 19
■ To discover how I/O is processed in Java (§19.2).
■ To distinguish between text I/O and binary I/O (§19.3).
■ To read and write bytes using FileInputStream and
FileOutputStream (§19.4.1).
■ To filter data using base classes
FilterInputStream/FilterOutputStream
(§19.4.2).
■ To read and write primitive values and strings using
DataInputStream/DataOutputStream (§19.4.3).
■ To store and restore objects using ObjectOutputStream
and ObjectInputStream, and to understand how objects
are serialized and what kind of objects can be
serialized (§19.6).
■ To implement the Serializable interface to make objects
serializable (§19.6.1).
■ To serialize arrays (§19.6.2).
■ To read and write files using the RandomAccessFile
class (§19.7).
M19_LIAN0807_08_SE_C19.QXD 11/24/09 10:52 AM Page
649
650 Chapter 19 Binary I/O
19.1 Introduction
Data stored in a text file are represented in human-readable
form. Data stored in a binary file
are represented in binary form. You cannot read binary files.
They are designed to be read by
programs. For example, Java source programs are stored in text
files and can be read by a text
editor, but Java classes are stored in binary files and are read by
the JVM. The advantage of
binary files is that they are more efficient to process than text
files.
Although it is not technically precise and correct, you can
envision a text file as consisting
of a sequence of characters and a binary file as consisting of a
sequence of bits. For example,
the decimal integer 199 is stored as the sequence of three
characters, '1', '9', '9', in a text
file, and the same integer is stored as a byte-type value C7 in a
binary file, because decimal
199 equals hex C7
Java offers many classes for performing file input and output.
These can be categorized as
text I/O classes and binary I/O classes. In §9.7, “File Input and
Output,” you learned how to
read/write strings and numeric values from/to a text file using
Scanner and PrintWriter.
This section introduces the classes for performing binary I/O.
19.2 How is I/O Handled in Java?
Recall that a File object encapsulates the properties of a file or
a path but does not contain
the methods for reading/writing data from/to a file. In order to
perform I/O, you need to cre-
ate objects using appropriate Java I/O classes. The objects
contain the methods for
reading/writing data from/to a file. For example, to write text to
a file named temp.txt, you
may create an object using the PrintWriter class as follows:
PrintWriter output = new PrintWriter("temp.txt");
You can now invoke the print method from the object to write a
string into the file. For
example, the following statement writes "Java 101" to the file.
output.print("Java 101");
The next statement closes the file.
output.close();
There are many I/O classes for various purposes. In general,
these can be classified as input
classes and output classes. An input class contains the methods
to read data, and an output
class contains the methods to write data. PrintWriter is an
example of an output class, and
Scanner is an example of an input class. The following code
creates an input object for the
file temp.txt and reads data from the file.
Scanner input = new Scanner(new File("temp.txt"));
System.out.println(input.nextLine());
If temp.txt contains "Java 101", input.nextLine() returns string
"Java 101".
Figure 19.1 illustrates Java I/O programming. An input object
reads a stream of data from
a file, and an output object writes a stream of data to a file. An
input object is also called an
input stream and an output object an output stream.
19.3 Text I/O vs. Binary I/O
Computers do not differentiate binary files and text files. All
files are stored in binary format, and
thus all files are essentially binary files. Text I/O is built upon
binary I/O to provide a level of
abstraction for character encoding and decoding, as shown in
Figure 19.2(a). Encoding and
decoding are automatically performed for text I/O. The JVM
converts a Unicode to a file-specific
1199 = 12 * 161 + 72.
text file
binary file
why binary I/O?
text I/O
binary I/O
input stream
output stream
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
650
19.3 Text I/O vs. Binary I/O 651
Program
Input object
created from an
input class
Output object
created from an
output class
Input stream
01011...1001
11001...1011
Output stream
File
File
FIGURE 19.1 The program receives data through an input
object and sends data through an
output object.
The same byte in the file
The encoding of the character
is stored in the file
Binary I/O program
Text I/O program
The Unicode of
the character
Encoding/
Decoding
A byte is read/written
e.g., "199"
e.g., 199
00110001 00111001 00111001
0x31
0xC7
0x39 0x39
00110111
(a)
(b)
FIGURE 19.2 Text I/O requires encoding and decoding, whereas
binary I/O does not.
encoding when writing a character and converts a file-specific
encoding to a Unicode when
reading a character. For example, suppose you write string
"199" using text I/O to a file. Each
character is written to the file. Since the Unicode for character
'1' is 0x0031, the Unicode
0x0031 is converted to a code that depends on the encoding
scheme for the file. (Note that the
prefix 0x denotes a hex number.) In the United States, the
default encoding for text files on Win-
dows is ASCII. The ASCII code for character '1' is 49 (0x31 in
hex) and for character '9' is
57 (0x39 in hex). So to write the characters "199", three bytes—
0x31, 0x39, and 0x39—are
sent to the output, as shown in Figure 19.2(a).
Note
The new version of Java supports supplementary Unicode. For
simplicity, however, this book con-
siders only the original Unicode from 0 to FFFF.
Binary I/O does not require conversions. If you write a numeric
value to a file using binary
I/O, the exact value in the memory is copied into the file. For
example, a byte-type value 199
is represented as 0xC7 in the memory and appears exactly as
0xC7 in
the file, as shown in Figure 19.2(b). When you read a byte using
binary I/O, one byte value is
read from the input.
In general, you should use text input to read a file created by a
text editor or a text output
program, and use binary input to read a file created by a Java
binary output program.
1199 = 12 * 161 + 72
supplementary Unicode
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
651
652 Chapter 19 Binary I/O
FileOutputStream
FilterOutputStream
ObjectOutputStream
FileInputStream
OutputStream
InputStream FilterInputStream
ObjectInputStream
Object
DataInputStream
BufferedInputStream
DataOutputStream
BufferedOutputStream
FIGURE 19.3 InputStream, OutputStream, and their subclasses
are for binary I/O.
java.io.InputStream
+read(): int
+read(b: byte[]): int
+read(b: byte[], off: int,
len: int): int
+available(): int
+close(): void
+skip(n: long): long
+markSupported(): boolean
+mark(readlimit: int): void
+reset(): void
Reads the next byte of data from the input stream. The value
byte is returned as
an int value in the range 0 to 255. If no byte is available
because the end of
the stream has been reached, the value –1 is returned.
Reads up to b.length bytes into array b from the input stream
and returns the
actual number of bytes read. Returns –1 at the end of the
stream.
Reads bytes from the input stream and stores them in b[off],
b[off+1], . . .,
b[off+len-1]. The actual number of bytes read is returned.
Returns –1
at the end of the stream.
Returns an estimate of the number of bytes that can be read
from the input stream.
Closes this input stream and releases any system resources
occupied by it.
Skips over and discards n bytes of data from this input stream.
The actual
number of bytes skipped is returned.
Tests whether this input stream supports the mark and reset
methods.
Marks the current position in this input stream.
Repositions this stream to the position at the time the mark
method was last
called on this input stream.
FIGURE 19.4 The abstract InputStream class defines the
methods for the input stream of bytes.
Binary I/O is more efficient than text I/O, because binary I/O
does not require encoding
and decoding. Binary files are independent of the encoding
scheme on the host machine and
thus are portable. Java programs on any machine can read a
binary file created by a Java pro-
gram. This is why Java class files are binary files. Java class
files can run on a JVM on any
machine.
Note
For consistency, this book uses the extension .txt to name text
files and .dat to name binary
files.
19.4 Binary I/O Classes
The design of the Java I/O classes is a good example of
applying inheritance, where common
operations are generalized in superclasses, and subclasses
provide specialized operations.
Figure 19.3 lists some of the classes for performing binary I/O.
InputStream is the root for
binary input classes, and OutputStream is the root for binary
output classes. Figures 19.4
and 19.5 list all the methods in InputStream and OutputStream.
.txt and .dat
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
652
19.4 Binary I/O Classes 653
java.io.InputStream
+FileInputStream(file: File)
+FileInputStream(filename: String)
javo.io.FileInputStream
Creates a FileInputStream from a File object.
Creates a FileInputStream from a file name.
FIGURE 19.5 The abstract OutputStream class defines the
methods for the output stream of bytes.
Creates a FileOutputStream from a File object.
Creates a FileOutputStream from a file name.
If append is true, data are appended to the existing file.
If append is true, data are appended to the existing file.
java.io.OutputStream
+FileOutputStream(file: File)
+FileOutputStream(filename: String)
+FileOutputStream(file: File, append: boolean)
+FileOutputStream(filename: String, append: boolean)
java.io.FileOutputStream
FIGURE 19.6 FileInputStream inputs a stream of bytes from a
file.
FIGURE 19.7 FileOutputStream outputs a stream of bytes to a
file.
java.io.OutputStream
+write(int b): void
+write(b: byte[], off: int,
len: int): void
+write(b: byte[]): void
+close(): void
+flush(): void
Writes the specified byte to this output stream. The parameter b
is an int value.
(byte)b is written to the output stream.
Writes b[off], b[off+1],. . ., b[off+len-1] into the output stream.
Writes all the bytes in array b to the output stream.
Closes this output stream and releases any system resources
occupied by it.
Flushes this output stream and forces any buffered output bytes
to be written out.
throws IOException
Note
All the methods in the binary I/O classes are declared to throw
java.io.IOException or a
subclass of java.io.IOException.
19.4.1 FileInputStream/FileOutputStream
FileInputStream/FileOutputStream is for reading/writing bytes
from/to files. All the
methods in these classes are inherited from InputStream and
OutputStream.
FileInputStream/FileOutputStream does not introduce new
methods. To construct a
FileInputStream, use the following constructors, as shown in
Figure 19.6:
FileNotFoundExceptionA java.io.FileNotFoundException will
occur if you attempt to create a File-
InputStream with a nonexistent file.
To construct a FileOutputStream, use the constructors shown in
Figure 19.7.
If the file does not exist, a new file will be created. If the file
already exists, the first two con-
structors will delete the current content of the file. To retain the
current content and append new
data into the file, use the last two constructors by passing true
to the append parameter.
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
653
654 Chapter 19 Binary I/O
public static void main(String[] args)
throws IOException {
// Perform I/O operations
}
Declaring exception in the method
public static void main(String[] args) {
try {
// Perform I/O operations
}
catch (IOException ex) {
ex.printStackTrace();
}
}
Using try-catch block
Almost all the methods in the I/O classes throw
java.io.IOException. Therefore you
have to declare java.io.IOException to throw in the method or
place the code in a try-
catch block, as shown below:
IOException
import
output stream
output
input stream
input
1 2 3 4 5 6 7 8 9 10
end of a file
A FileOutputStream is created for file temp.dat in line 6. The
for loop writes ten
byte values into the file (lines 9–10). Invoking write(i) is the
same as invoking
write((byte)i). Line 13 closes the output stream. Line 16 creates
a FileInputStream
for file temp.dat. Values are read from the file and displayed on
the console in lines 19–21.
The expression ((value = input.read()) != -1) (line 20) reads a
byte from
input.read(), assigns it to value, and checks whether it is –1.
The input value of –1
signifies the end of a file.
Listing 19.1 uses binary I/O to write ten byte values from 1 to
10 to a file named temp.dat
and reads them back from the file.
LISTING 19.1 TestFileStream.java
1 import java.io.*;
2
3 public class TestFileStream {
4 public static void main(String[] args) {
5 // Create an output stream to the file
6
7
8 // Output values to the file
9 for (int i = 1; i <= 10; i++)
10
11
12 // Close the output stream
13
14
15 // Create an input stream for the file
16
17
18 // Read values from the file
19 int value;
20 while ((value = ) != -1)
21 System.out.print(value + " ");
22
23 // Close the output stream
24
25 }
26 }
input.close();
input.read()
FileInputStream input = new FileInputStream("temp.dat");
output.close();
output.write(i);
FileOutputStream output = new FileOutputStream("temp.dat");
throws IOException
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
654
19.4 Binary I/O Classes 655
FIGURE 19.8 A binary file cannot be displayed in text mode.
Binary data
The file temp.dat created in this example is a binary file. It can
be read from a Java
program but not from a text editor, as shown in Figure 19.8.
Tip
When a stream is no longer needed, always close it using the
close() method. Not closing
streams may cause data corruption in the output file, or other
programming errors.
Note
The root directory for the file is the classpath directory. For the
example in this book, the root
directory is c:book. So the file temp.dat is located at c:book. If
you wish to place temp.dat
in a specific directory, replace line 8 by
FileOutputStream output =
new FileOutputStream("directory/temp.dat");
Note
An instance of FileInputStream can be used as an argument to
construct a Scanner, and
an instance of FileOutputStream can be used as an argument to
construct a
PrintWriter. You can create a PrintWriter to append text into a
file using
new PrintWriter(new FileOutputStream("temp.txt", true));
If temp.txt does not exist, it is created. If temp.txt already
exists, new data are appended to the file.
19.4.2 FilterInputStream/FilterOutputStream
Filter streams are streams that filter bytes for some purpose.
The basic byte input stream pro-
vides a read method that can be used only for reading bytes. If
you want to read integers,
doubles, or strings, you need a filter class to wrap the byte input
stream. Using a filter class
enables you to read integers, doubles, and strings instead of
bytes and characters.
FilterInputStream and FilterOutputStream are the base classes
for filtering data.
When you need to process primitive numeric types, use
DataInputStream and
DataOutputStream to filter bytes.
19.4.3 DataInputStream/DataOutputStream
DataInputStream reads bytes from the stream and converts them
into appropriate primitive
type values or strings. DataOutputStream converts primitive
type values or strings into
bytes and outputs the bytes to the stream.
DataInputStream extends FilterInputStream and implements the
DataInput
interface, as shown in Figure 19.9. DataOutputStream extends
FilterOutputStream
and implements the DataOutput interface, as shown in Figure
19.10.
DataInputStream implements the methods defined in the
DataInput interface to read
primitive data type values and strings. DataOutputStream
implements the methods defined
in the DataOutput interface to write primitive data type values
and strings. Primitive values
close stream
where is the file?
appending to text file
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
655
656 Chapter 19 Binary I/O
FIGURE 19.10 DataOutputStream enables you to write
primitive data type values and strings into an output stream.
+writeChar(c: char): void
+writeChars(s: String): void
+writeBoolean(b: boolean): void
+writeByte(v: int): void
+writeBytes(s: String): void
+writeFloat(v: float): void
+writeDouble(v: double): void
+writeInt(v: int): void
+writeLong(v: long): void
+writeShort(v: short): void
+writeUTF(s: String): void
Writes a Boolean to the output stream.
Writes the eight low-order bits of the argument v to
the output stream.
Writes the lower byte of the characters in a string to
the output stream.
Writes a character (composed of 2 bytes) to the
output stream.
Writes every character in the string s to the output
stream, in order, 2 bytes per character.
Writes a float value to the output stream.
Writes a double value to the output stream.
Writes an int value to the output stream.
Writes a long value to the output stream.
Writes a short value to the output stream.
Writes s string in UTF format.
OutputStream
FilterOutputStream
DataOutputStream
+DataOutputStream
(out: OutputStream)
«interface»
java.io.DataOutput
are copied from memory to the output without any conversions.
Characters in a string may be
written in several ways, as discussed in the next section.
Characters and Strings in Binary I/O
A Unicode consists of two bytes. The writeChar(char c) method
writes the Unicode of
character c to the output. The writeChars(String s) method
writes the Unicode for each
character in the string s to the output. The writeBytes(String s)
method writes the lower
byte of the Unicode for each character in the string s to the
output. The high byte of the Uni-
code is discarded. The writeBytes method is suitable for strings
that consist of ASCII char-
acters, since an ASCII code is stored only in the lower byte of a
Unicode. If a string consists
of non-ASCII characters, you have to use the writeChars method
to write the string.
The writeUTF(String s) method writes two bytes of length
information to the output
stream, followed by the modified UTF-8 representation of every
character in the string s.
UTF-8 is a coding scheme that allows systems to operate with
both ASCII and Unicode. Most
operating systems use ASCII. Java uses Unicode. The ASCII
character set is a subset of the
Unicode character set. Since most applications need only the
ASCII character set, it is a waste
to represent an 8-bit ASCII character as a 16-bit Unicode
character. The modified UTF-8
scheme stores a character using one, two, or three bytes.
Characters are coded in one byte if
+readBoolean(): boolean
+readByte(): byte
+readChar(): char
+readFloat(): float
+readDouble(): double
+readInt(): int
+readLong(): long
+readShort(): short
+readLine(): String
+readUTF(): String
Reads a Boolean from the input stream.
Reads a byte from the input stream.
Reads a character from the input stream.
Reads a float from the input stream.
Reads a double from the input stream.
Reads an int from the input stream.
Reads a long from the input stream.
Reads a short from the input stream.
Reads a line of characters from input.
Reads a string in UTF format.
InputStream
FilterInputStream
DataInputStream
+DataInputStream(
in: InputStream)
«interface»
java.io.DataInput
FIGURE 19.9 DataInputStream filters an input stream of bytes
into primitive data type values and strings.
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
656
19.4 Binary I/O Classes 657
their code is less than or equal to 0x7F, in two bytes if their
code is greater than 0x7F and less
than or equal to 0x7FF, or in three bytes if their code is greater
than 0x7FF.
The initial bits of a UTF-8 character indicate whether a
character is stored in one byte, two
bytes, or three bytes. If the first bit is 0, it is a one-byte
character. If the first bits are 110, it is
the first byte of a two-byte sequence. If the first bits are 1110,
it is the first byte of a three-byte
sequence. The information that indicates the number of
characters in a string is stored in the
first two bytes preceding the UTF-8 characters. For example,
writeUTF("ABCDEF") actu-
ally writes eight bytes (i.e., 00 06 41 42 43 44 45 46) to the file,
because the first two bytes
store the number of characters in the string.
The writeUTF(String s) method converts a string into a series of
bytes in the UTF-8
format and writes them into a binary stream. The readUTF()
method reads a string that has
been written using the writeUTF method.
The UTF-8 format has the advantage of saving a byte for each
ASCII character, because a
Unicode character takes up two bytes and an ASCII character in
UTF-8 only one byte. If most
of the characters in a long string are regular ASCII characters,
using UTF-8 is efficient.
Using DataInputStream/DataOutputStream
Data streams are used as wrappers on existing input, and output
streams to filter data in the orig-
inal stream. They are created using the following constructors
(see Figures 19.9 and 19.10):
public DataInputStream(InputStream instream)
public DataOutputStream(OutputStream outstream)
The statements given below create data streams. The first
statement creates an input stream
for file in.dat; the second statement creates an output stream for
file out.dat.
DataInputStream input =
(new FileInputStream("in.dat"));
DataOutputStream output =
(new FileOutputStream("out.dat"));
Listing 19.2 writes student names and scores to a file named
temp.dat and reads the data back
from the file.
LISTING 19.2 TestDataStream.java
1 import java.io.*;
2
3 public class TestDataStream {
4 public static void main(String[] args) throws IOException {
5 // Create an output stream for file temp.dat
6
7
8
9 // Write student test scores to the file
10
11
12 output.writeUTF("Jim");
13 output.writeDouble(185.5);
14 output.writeUTF("George");
15 output.writeDouble(105.25);
16
17 // Close output stream
18 output.close();
19
20 // Create an input stream for file temp.dat
21
22
23
new DataInputStream(new FileInputStream("temp.dat"));
DataInputStream input =
output.writeDouble(85.5);
output.writeUTF("John");
new DataOutputStream(new FileOutputStream("temp.dat"));
DataOutputStream output =
new DataOutputStream
new DataInputStream
UTF-8 scheme
output stream
output
close stream
input stream
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
657
658 Chapter 19 Binary I/O
input
John 85.5
Jim 185.5
George 105.25
A DataOutputStream is created for file temp.dat in lines 6–7.
Student names and scores
are written to the file in lines 10–15. Line 18 closes the output
stream. A DataInputStream
is created for the same file in lines 21–22. Student names and
scores are read back from the
file and displayed on the console in lines 25–27.
DataInputStream and DataOutputStream read and write Java
primitive type values
and strings in a machine-independent fashion, thereby enabling
you to write a data file on one
machine and read it on another machine that has a different
operating system or file structure.
An application uses a data output stream to write data that can
later be read by a program
using a data input stream.
Caution
You have to read data in the same order and format in which
they are stored. For example, since
names are written in UTF-8 using writeUTF, you must read
names using readUTF.
Detecting End of File
If you keep reading data at the end of an InputStream, an
EOFException will occur. This
exception may be used to detect the end of file, as shown in
Listing 19.3.
LISTING 19.3 DetectEndOfFile.java
1 import java.io.*;
2
3 public class DetectEndOfFile {
4 public static void main(String[] args) {
5 try {
6 DataOutputStream output = new DataOutputStream
7 (new FileOutputStream("test.dat"));
8 output.writeDouble(4.5);
9 output.writeDouble(43.25);
10 output.writeDouble(3.2);
11 output.close();
12
13 DataInputStream input = new DataInputStream
14 (new FileInputStream("test.dat"));
15 while (true) {
16 System.out.println( );
17 }
18 }
19
20 System.out.println("All data read");
21 }
22 catch (IOException ex) {
23 ex.printStackTrace();
24 }
25 }
26 }
catch (EOFException ex) {
input.readDouble()
EOFException
output stream
output
close stream
input stream
input
EOFException
24 // Read student test scores from the file
25 System.out.println( + " " + );
26 System.out.println(input.readUTF() + " " +
input.readDouble());
27 System.out.println(input.readUTF() + " " +
input.readDouble());
28 }
29 }
input.readDouble()input.readUTF()
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
658
19.4 Binary I/O Classes 659
FIGURE 19.11 BufferedInputStream buffers input stream.
4.5
43.25
3.2
All data read
Creates a BufferedInputStream from an
InputStream object.
Creates a BufferedInputStream from an
InputStream object with specified buffer size.
+BufferedInputStream(in: InputStream)
+BufferedInputStream(filename: String, bufferSize: int)
java.io.InputStream
java.io.FilterInputStream
java.io.BufferedInputStream
The program writes three double values to the file using
DataOutputStream (lines 6–10),
and reads the data using DataInputStream (lines 13–17). When
reading past the end of file,
an EOFException is thrown. The exception is caught in line 19.
19.4.4 BufferedInputStream/BufferedOutputStream
BufferedInputStream/BufferedOutputStream can be used to
speed up input and
output by reducing the number of reads and writes.
BufferedInputStream/
BufferedOutputStream does not contain new methods. All the
methods in
BufferedInputStream/BufferedOutputStream are inherited from
the InputStream/
OutputStream classes.
BufferedInputStream/BufferedOutputStream adds a buffer in
the stream for storing bytes for efficient processing.
You may wrap a BufferedInputStream/BufferedOutputStream on
any
InputStream/OutputStream using the constructors shown in
Figures 19.11 and 19.12.
Creates a BufferedOutputStream from an
OutputStream object.
Creates a BufferedOutputStream from an
OutputStream object with specified size.
+BufferedOutputStream(out: OutputStream)
+BufferedOutputStream(filename: String, bufferSize: int)
java.io.OutputStream
java.io.FilterOutputStream
java.io.BufferedOutputStream
FIGURE 19.12 BufferedOutputStream buffers output stream.
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
659
660 Chapter 19 Binary I/O
File exists
Delete file
Copy
Source does
not exist
FIGURE 19.13 The program copies a file.
If no buffer size is specified, the default size is 512 bytes. A
buffered input stream reads as
many data as possible into its buffer in a single read call. By
contrast, a buffered output stream
calls the write method only when its buffer fills up or when the
flush() method is called.
You can improve the performance of the TestDataStream
program in the preceding
example by adding buffers in the stream in lines 6–7 and 13–14
as follows:
DataOutputStream output = new DataOutputStream(
(new FileOutputStream("temp.dat")));
DataInputStream input = new DataInputStream(
(new FileInputStream("temp.dat")));
Tip
You should always use buffered IO to speed up input and
output. For small files, you may not
notice performance improvements. However, for large files—
over 100 MB—you will see substan-
tial improvements using buffered IO.
19.5 Problem: Copying Files
This section develops a program that copies files. The user
needs to provide a source file and
a target file as command-line arguments using the following
command:
java Copy source target
The program copies a source file to a target file and displays the
number of bytes in the file. If
the source does not exist, the user is told that the file has not
been found. If the target file
already exists, the user is told that the file exists. A sample run
of the program is shown in
Figure 19.13.
new BufferedInputStream
new BufferedOutputStream
To copy the contents from a source to a target file, it is
appropriate to use a binary input
stream to read bytes from the source file and a binary output
stream to send bytes to the target
file, regardless of the contents of the file. The source file and
the target file are specified from
the command line. Create an InputFileStream for the source file
and an
OutputFileStream for the target file. Use the read() method to
read a byte from the input
stream, and then use the write(b) method to write the byte to the
output stream. Use
BufferedInputStream and BufferedOutputStream to improve the
performance. Listing
19.4 gives the solution to the problem.
Video Note
Copy file
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
660
19.5 Problem: Copying Files 661
LISTING 19.4 Copy.java
1 import java.io.*;
2
3 public class Copy {
4 /** Main method
5 @param args[0] for sourcefile
6 @param args[1] for target file
7 */
8 public static void main(String[] args) throws IOException {
9 // Check command-line parameter usage
10 if (args.length != 2) {
11 System.out.println(
12 "Usage: java Copy sourceFile targetfile");
13 System.exit(0);
14 }
15
16 // Check whether source file exists
17
18 if (!sourceFile.exists()) {
19 System.out.println("Source file " + args[0] + " not
exist");
20 System.exit(0);
21 }
22
23 // Check whether target file exists
24
25 if (targetFile.exists()) {
26 System.out.println("Target file " + args[1] + " already
27 exists");
28 System.exit(0);
29 }
30
31 // Create an input stream
32
33
34
35 // Create an output stream
36
37
38
39 // Continuously read a byte from input and write it to
output
40 int r; int numberOfBytesCopied = 0;
41 while (( ) != -1) {
42
43 numberOfBytesCopied++;
44 }
45
46 // Close streams
47 input.close();
48 output.close();
49
50 // Display the file size
51 System.out.println(numberOfBytesCopied + " bytes
copied");
52 }
53 }
The program first checks whether the user has passed two
required arguments from the com-
mand line in lines 10–14.
The program uses the File class to check whether the source file
and target file exist. If
the source file does not exist (lines 18–21) or if the target file
already exists, exit the program.
output.write((byte)r);
r = input.read()
new BufferedOutputStream(new FileOutputStream(targetFile));
BufferedOutputStream output =
new BufferedInputStream(new FileInputStream(sourceFile));
BufferedInputStream input =
File targetFile = new File(args[1]);
File sourceFile = new File(args[0]);
check usage
source file
target file
input stream
output stream
read
write
close stream
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
661
662 Chapter 19 Binary I/O
Reads an object.
java.io.InputStream
java.io.ObjectInputStream
+ObjectInputStream(in: InputStream) +readObject(): Object
«interface»
java.io.DataInput
«interface»
java.io.ObjectInput
«interface»
ObjectStreamConstants
FIGURE 19.14 ObjectInputStream can read objects, primitive
type values, and strings.
Writes an object.
java.io.OutputStream
java.io.ObjectOutputStream
+ObjectOutputStream(out: OutputStream) +writeObject(o:
Object): void
«interface»
java.io.DataOutput
«interface»
java.io.ObjectOutput
«interface»
ObjectStreamConstants
FIGURE 19.15 ObjectOutputStream can write objects, primitive
type values, and strings.
An input stream is created using BufferedInputStream wrapped
on FileInputStream
in lines 32–33, and an output stream is created using
BufferedOutputStream wrapped on
FileOutputStream in lines 36–37.
The expression ((r = input.read()) != -1) (line 41) reads a byte
from input.
read(), assigns it to r, and checks whether it is –1. The input
value of –1 signifies the end of
a file. The program continuously reads bytes from the input
stream and sends them to the out-
put stream until all of the bytes have been read.
19.6 Object I/O
DataInputStream/DataOutputStream enables you to perform I/O
for primitive type
values and strings. ObjectInputStream/ObjectOutputStream
enables you to perform
I/O for objects in addition to primitive type values and strings.
Since ObjectInputStream/
ObjectOutputStream contains all the functions of
DataInputStream/
DataOutputStream, you can replace
DataInputStream/DataOutputStream com-
pletely with ObjectInputStream/ObjectOutputStream.
ObjectInputStream extends InputStream and implements
ObjectInput and
ObjectStreamConstants, as shown in Figure 19.14. ObjectInput
is a subinterface of
DataInput. DataInput is shown in Figure 19.9.
ObjectStreamConstants contains the
constants to support ObjectInputStream/ObjectOutputStream.
ObjectOutputStream extends OutputStream and implements
ObjectOutput and
ObjectStreamConstants, as shown in Figure 19.15. ObjectOutput
is a subinterface of
DataOutput. DataOutput is shown in Figure 19.10.
Video Note
Object I/O
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
662
19.6 Object I/O 663
You may wrap an ObjectInputStream/ObjectOutputStream on
any InputStream/
OutputStream using the following constructors:
// Create an ObjectInputStream
public ObjectInputStream(InputStream in)
// Create an ObjectOutputStream
public ObjectOutputStream(OutputStream out)
Listing 19.5 writes student names, scores, and current date to a
file named object.dat.
LISTING 19.5 TestObjectOutputStream.java
1 import java.io.*;
2
3 public class TestObjectOutputStream {
4 public static void main(String[] args) throws IOException {
5 // Create an output stream for file object.dat
6
7
8
9 // Write a string, double value, and object to the file
10 output.writeUTF("John");
11 output.writeDouble(85.5);
12
13
14 // Close output stream
15 output.close();
16 }
17 }
An ObjectOutputStream is created to write data into file
object.dat in lines 6–7. A string,
a double value, and an object are written to the file in lines 10–
12. To improve performance,
you may add a buffer in the stream using the following
statement to replace lines 6–7:
ObjectOutputStream output = new ObjectOutputStream(
new BufferedOutputStream(new
FileOutputStream("object.dat")));
Multiple objects or primitives can be written to the stream. The
objects must be read back
from the corresponding ObjectInputStream with the same types
and in the same order as
they were written. Java’s safe casting should be used to get the
desired type. Listing 19.6 reads
data back from object.dat.
LISTING 19.6 TestObjectInputStream.java
1 import java.io.*;
2
3 public class TestObjectInputStream {
4 public static void main(String[] args)
5 throws ClassNotFoundException, IOException {
6 // Create an input stream for file object.dat
7
8
9
10 // Write a string, double value, and object to the file
11 String name = input.readUTF();
12 double score = input.readDouble();
13 java.util.Date date = (java.util.Date)( );
14 System.out.println(name + " " + score + " " + date);
15
input.readObject()
new ObjectInputStream(new FileInputStream("object.dat"));
ObjectInputStream input =
output.writeObject(new java.util.Date());
new ObjectOutputStream(new FileOutputStream("object.dat"));
ObjectOutputStream output = output stream
output
input stream
input
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
663
664 Chapter 19 Binary I/O
16 // Close output stream
17 input.close();
18 }
19 }
John 85.5 Mon Jun 26 17:17:29 EDT 2006
The readObject()method may throw java.lang.
ClassNotFoundException. The reason
is that when the JVM restores an object, it first loads the class
for the object if the class has not
been loaded. Since ClassNotFoundException is a checked
exception, the main method
declares to throw it in line 5. An ObjectInputStream is created
to read input from object.dat in
lines 7–8. You have to read the data from the file in the same
order and format as they were written
to the file. A string, a double value, and an object are read in
lines 11–13. Since readObject()
returns an Object, it is cast into Date and assigned to a Date
variable in line 13.
19.6.1 The Serializable Interface
Not every object can be written to an output stream. Objects
that can be so written are said to
be serializable. A serializable object is an instance of the
java.io.Serializable inter-
face, so the object’s class must implement Serializable.
The Serializable interface is a marker interface. Since it has no
methods, you don’t need to
add additional code in your class that implements Serializable.
Implementing this interface
enables the Java serialization mechanism to automate the
process of storing objects and arrays.
To appreciate this automation feature, consider what you
otherwise need to do in order to
store an object. Suppose you want to store a JButton object. To
do this you need to store all
the current values of the properties (e.g., color, font, text,
alignment) in the object. Since
JButton is a subclass of AbstractButton, the property values of
AbstractButton have
to be stored as well as the properties of all the superclasses of
AbstractButton. If a prop-
erty is of an object type (e.g., background of the Color type),
storing it requires storing all
the property values inside this object. As you can see, this is a
very tedious process. Fortu-
nately, you don’t have to go through it manually. Java provides
a built-in mechanism to auto-
mate the process of writing objects. This process is referred to
as object serialization, which
is implemented in ObjectOutputStream. In contrast, the process
of reading objects is
referred to as object deserialization, which is implemented in
ObjectInputStream.
Many classes in the Java API implement Serializable. The
utility classes, such as
java.util.Date, and all the Swing GUI component classes
implement Serializable.
Attempting to store an object that does not support the
Serializable interface would cause
a NotSerializableException.
When a serializable object is stored, the class of the object is
encoded; this includes the class
name and the signature of the class, the values of the object’s
instance variables, and the closure
of any other objects referenced from the initial object. The
values of the object’s static variables
are not stored.
Note
nonserializable fields
If an object is an instance of Serializable but contains
nonserializable instance data fields,
can it be serialized? The answer is no. To enable the object to
be serialized, mark these data fields
with the transient keyword to tell the JVM to ignore them when
writing the object to an
object stream. Consider the following class:
public class Foo implements java.io.Serializable {
private int v1;
private double v2;
private A v3 = new A();
}
class A { } // A is not serializable
transient
static
ClassNotFoundException
serializable
serialization
deserialization
NotSerializable-
Exception
transient
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
664
19.6 Object I/O 665
When an object of the Foo class is serialized, only variable v1
is serialized. Variable v2 is not
serialized because it is a static variable, and variable v3 is not
serialized because it is marked
transient. If v3 were not marked transient, a
java.io.NotSerializable-
Exception would occur.
Note
duplicate objects
If an object is written to an object stream more than once, will
it be stored in multiple copies? No,
it will not. When an object is written for the first time, a serial
number is created for it. The JVM
writes the complete content of the object along with the serial
number into the object stream.
After the first time, only the serial number is stored if the same
object is written again. When the
objects are read back, their references are the same, since only
one object is actually created in the
memory.
19.6.2 Serializing Arrays
An array is serializable if all its elements are serializable. An
entire array can be saved using
writeObject into a file and later can be restored using
readObject. Listing 19.7 stores an array
of five int values and an array of three strings and reads them
back to display on the console.
LISTING 19.7 TestObjectStreamForArray.java
1 import java.io.*;
2
3 public class TestObjectStreamForArray {
4 public static void main(String[] args)
5 throws ClassNotFoundException, IOException {
6 int[] numbers = {1, 2, 3, 4, 5};
7 String[] strings = {"John", "Jim", "Jake"};
8
9 // Create an output stream for file array.dat
10
11
12
13
14 // Write arrays to the object output stream
15
16
17
18 // Close the stream
19 output.close();
20
21 // Create an input stream for file array.dat
22
23
24
25
26
27
28 // Display arrays
29 for (int i = 0; i < newNumbers.length; i++)
30 System.out.print(newNumbers[i] + " ");
31 System.out.println();
32
33 for (int i = 0; i < newStrings.length; i++)
34 System.out.print(newStrings[i] + " ");
35 }
36 }
String[] newStrings = (String[])(input.readObject());
int[] newNumbers = (int[])(input.readObject());
new ObjectInputStream(new FileInputStream("array.dat"));
ObjectInputStream input =
output.writeObject(strings);
output.writeObject(numbers);
("array.dat", true));
new ObjectOutputStream(new FileOutputStream
ObjectOutputStream output = output stream
store array
input stream
restore array
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
665
666 Chapter 19 Binary I/O
Creates a RandomAccessFile stream with the specified File
object
and mode.
Creates a RandomAccessFile stream with the specified file
name,
string, and mode.
Closes the stream and releases the resource associated with it.
Returns the offset, in bytes, from the beginning of the file to
where the
next read or write occurs.
Returns the length of this file.
Reads a byte of data from this file and returns –1 at the end of
stream.
Reads up to b.length bytes of data from this file into an array of
bytes.
Reads up to len bytes of data from this file into an array of
bytes.
Sets the offset (in bytes specified in pos) from the beginning of
the
stream to where the next read or write occurs.
Sets a new length for this file.
Skips over n bytes of input.
Writes b.length bytes from the specified byte array to this file,
starting at the current file pointer.
Writes len bytes from the specified byte array, starting at offset
off,
to this file.
java.io.RandomAccessFile
+RandomAccessFile(file: File, mode:
String)
+RandomAccessFile(name: String,
mode: String)
+close(): void
+getFilePointer(): long
+length(): long
+read(): int
+read(b: byte[]): int
+read(b: byte[], off: int, len: int): int
+seek(pos: long): void
+setLength(newLength: long): void
+skipBytes(int n): int
+write(b: byte[]): void
+write(b: byte[], off: int, len: int):
void
«interface»
java.io.DataOutput
«interface»
java.io.DataInput
FIGURE 19.16 RandomAccessFile implements the DataInput
and DataOutput interfaces with additional methods
to support random access.
1 2 3 4 5
John Jim Jake
Lines 15–16 write two arrays into file array.dat. Lines 25–26
read three arrays back in the
same order they were written. Since readObject() returns
Object, casting is used to cast
the objects into int[] and String[].
19.7 Random-Access Files
All of the streams you have used so far are known as read-only
or write-only streams. The exter-
nal files of these streams are sequential files that cannot be
updated without creating a new file.
It is often necessary to modify files or to insert new records into
files. Java provides the
RandomAccessFile class to allow a file to be read from and
written to at random locations.
The RandomAccessFile class implements the DataInput and
DataOutput interfaces,
as shown in Figure 19.16. The DataInput interface shown in
Figure 19.9 defines the meth-
ods (e.g., readInt, readDouble, readChar, readBoolean,
readUTF) for reading primi-
tive type values and strings, and the DataOutput interface
shown in Figure 19.10 defines the
methods (e.g., writeInt, writeDouble, writeChar, writeBoolean,
writeUTF) for
writing primitive type values and strings.
read-only
write-only
sequential
When creating a RandomAccessFile, you can specify one of two
modes (“r” or “rw”).
Mode “r” means that the stream is read-only, and mode “rw”
indicates that the stream allows
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
666
19.7 Random-Access Files 667
both read and write. For example, the following statement
creates a new stream, raf, that
allows the program to read from and write to the file test.dat:
RandomAccessFile raf = new RandomAccessFile("test.dat",
"rw");
If test.dat already exists, raf is created to access it; if test.dat
does not exist, a new file
named test.dat is created, and raf is created to access the new
file. The method
raf.length() returns the number of bytes in test.dat at any given
time. If you append new
data into the file, raf.length() increases.
Tip
If the file is not intended to be modified, open it with the "r"
mode. This prevents unintentional
modification of the file.
A random-access file consists of a sequence of bytes. A special
marker called a file pointer is
positioned at one of these bytes. A read or write operation takes
place at the location of the file
pointer. When a file is opened, the file pointer is set at the
beginning of the file. When you
read or write data to the file, the file pointer moves forward to
the next data item. For exam-
ple, if you read an int value using readInt(), the JVM reads 4
bytes from the file pointer,
and now the file pointer is 4 bytes ahead of the previous
location, as shown in Figure 19.17.
file pointer
For a RandomAccessFile raf, you can use the raf.seek(position)
method to move
the file pointer to a specified position. raf.seek(0) moves it to
the beginning of the file, and
raf.seek(raf.length()) moves it to the end of the file. Listing
19.8 demonstrates
RandomAccessFile. A large case study of using
RandomAccessFile to organize an
address book is given in Supplement VII.B.
LISTING 19.8 TestRandomAccessFile.java
1 import java.io.*;
2
3 public class TestRandomAccessFile {
4 public static void main(String[] args) throws IOException {
5 // Create a random-access file
6
7
8 // Clear the file to destroy the old contents, if any
9
10
11 // Write new integers to the file
12 for (int i = 0; i < 200; i++)
13
14
15 // Display the current length of the file
16 System.out.println("Current file length is " + );
17
inout.length()
inout.writeInt(i);
inout.setLength(0);
RandomAccessFile inout = new RandomAccessFile("inout.dat",
"rw"); RandomAccessFile
empty file
write
(b) After readInt()
File pointer
File
File
… byte byte byte byte byte byte byte byte byte byte… (a)
Before readInt()byte byte
byte byte byte byte byte bytebyte byte byte byte byte… …byte
File pointer
FIGURE 19.17 After an int value is read, the file pointer is
moved 4 bytes ahead.
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
667
668 Chapter 19 Binary I/O
18 // Retrieve the first number
19 // Move the file pointer to the beginning
20 System.out.println("The first number is " + );
21
22 // Retrieve the second number
23 // Move the file pointer to the second number
24 System.out.println("The second number is " + );
25
26 // Retrieve the tenth number
27 // Move the file pointer to the tenth number
28 System.out.println("The tenth number is " + );
29
30 // Modify the eleventh number
31
32
33 // Append a new number
34 // Move the file pointer to the end
35
36
37 // Display the new length
38 System.out.println("The new length is " + );
39
40 // Retrieve the new eleventh number
41 // Move the file pointer to the next number
42 System.out.println("The eleventh number is " + );
43
44 inout.close();
45 }
46 }
inout.readInt()
inout.seek(10 * 4);
inout.length()
inout.writeInt(999);
inout.seek(inout.length());
inout.writeInt(555);
inout.readInt()
inout.seek(9 * 4);
inout.readInt()
inout.seek(1 * 4);
inout.readInt()
inout.seek(0);move pointer
read
close file
Current file length is 800
The first number is 0
The second number is 1
The tenth number is 9
The new length is 804
The eleventh number is 555
A RandomAccessFile is created for the file named inout.dat
with mode “rw” to allow both
read and write operations in line 6.
inout.setLength(0) sets the length to 0 in line 9. This, in effect,
destroys the old con-
tents of the file.
The for loop writes 200 int values from 0 to 199 into the file in
lines 12–13. Since each
int value takes 4 bytes, the total length of the file returned from
inout.length() is now
800 (line 16), as shown in sample output.
Invoking inout.seek(0) in line 19 sets the file pointer to the
beginning of the file.
inout.readInt() reads the first value in line 20 and moves the file
pointer to the next num-
ber. The second number is read in line 23.
inout.seek(9 * 4) (line 27) moves the file pointer to the tenth
number. inout
.readInt() reads the tenth number and moves the file pointer to
the eleventh number in
line 28. inout.write(555) writes a new eleventh number at the
current position (line 31).
The previous eleventh number is destroyed.
inout.seek(inout.length()) moves the file pointer to the end of
the file (line 34).
inout.writeInt(999) writes a 999 to the file. Now the length of
the file is increased by 4,
so inout.length() returns 804 (line 38).
inout.seek(10 * 4) moves the file pointer to the eleventh number
in line 41. The new
eleventh number, 555, is displayed in line 42.
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
668
Review Questions 669
KEY TERMS
binary I/O 650
deserialization 664
file pointer 667
random-access file 667
sequential-access file 666
serialization 664
stream 650
text I/O 650
CHAPTER SUMMARY
1. I/O can be classified into text I/O and binary I/O. Text I/O
interprets data in sequences
of characters. Binary I/O interprets data as raw binary values.
How text is stored in a file
depends on the encoding scheme for the file. Java automatically
performs encoding and
decoding for text I/O.
2. The InputStream and OutputStream classes are the roots of
all binary I/O classes.
FileInputStream/FileOutputStream associates a file for binary
input/output.
BufferedInputStream/BufferedOutputStream can be used to
wrap on any
binary I/O stream to improve performance.
DataInputStream/DataOutputStream
can be used to read/write primitive values and strings.
3. ObjectInputStream/ObjectOutputStream can be used to
read/write objects in
addition to primitive values and strings. To enable object
serialization, the object’s
defining class must implement the java.io.Serializable marker
interface.
4. The RandomAccessFile class enables you to read and write
data to a file. You can
open a file with the “r” mode to indicate that it is read-only, or
with the “rw” mode to
indicate that it is updateable. Since the RandomAccessFile class
implements
DataInput and DataOutput interfaces, many methods in
RandomAccessFile are
the same as those in DataInputStream and DataOutputStream.
REVIEW QUESTIONS
Sections 19.1–19.2
19.1 What is a text file, and what is a binary file? Can you view
a text file or a binary
file using a text editor?
19.2 How do you read or write data in Java? What is a stream?
Section 19.3
19.3 What are the differences between text I/O and binary I/O?
19.4 How is a Java character represented in the memory, and
how is a character repre-
sented in a text file?
19.5 If you write string “ABC” to an ASCII text file, what
values are stored in the file?
19.6 If you write string “100” to an ASCII text file, what values
are stored in the file?
If you write a numeric byte-type value 100 using binary I/O,
what values are
stored in the file?
19.7 What is the encoding scheme for representing a character
in a Java program? By
default, what is the encoding scheme for a text file on
Windows?
Section 19.4
19.8 Why do you have to declare to throw IOException in the
method or use a try-
catch block to handle IOException for Java IO programs?
19.9 Why should you always close streams?
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
669
670 Chapter 19 Binary I/O
19.10 InputStream reads bytes. Why does the read() method
return an int instead
of a byte? Find the abstract methods in InputStream and
OutputStream.
19.11 Does FileInputStream/FileOutputStream introduce any
new methods?
How do you create a FileInputStream/FileOutputStream?
19.12 What will happen if you attempt to create an input stream
on a nonexistent file?
What will happen if you attempt to create an output stream on
an existing file? Can
you append data to an existing file?
19.13 How do you append data to an existing text file using
java.io.PrintWriter?
19.14 Suppose a file contains an unspecified number of double
values. Theses values
were written to the file using the writeDouble method using a
DataOutputStream. How do you write a program to read all
these values? How
do you detect the end of file?
19.15 What is written to a file using writeByte(91) on a
FileOutputStream?
19.16 How do you check the end of a file in a binary input
stream (FileInputStream,
DataInputStream)?
19.17 What is wrong in the following code?
import java.io.*;
public class Test {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("test.dat");
}
catch (IOException ex) {
ex.printStackTrace();
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}
19.18 Suppose you run the program on Windows using the
default ASCII encoding.
After the program is finished, how many bytes are in the file
t.txt? Show the con-
tents of each byte.
public class Test {
public static void main(String[] args)
throws java.io.IOException {
java.io.PrintWriter output =
new java.io.PrintWriter("t.txt");
output.printf("%s", "1234");
output.printf("%s", "5678");
output.close();
}
}
19.19 After the program is finished, how many bytes are in the
file t.dat? Show the con-
tents of each byte.
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
DataOutputStream output = new DataOutputStream(
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
670
Review Questions 671
new FileOutputStream("t.dat"));
output.writeInt(1234);
output.writeInt(5678);
output.close();
}
}
19.20 For each of the following statements on a
DataOutputStream out, how many
bytes are sent to the output?
output.writeChar('A');
output.writeChars("BC");
output.writeUTF("DEF");
19.21 What are the advantages of using buffered streams? Are
the following statements
correct?
BufferedInputStream input1 =
new BufferedInputStream(new FileInputStream("t.dat"));
DataInputStream input2 = new DataInputStream(
new BufferedInputStream(new FileInputStream("t.dat")));
ObjectInputStream input3 = new ObjectInputStream(
new BufferedInputStream(new FileInputStream("t.dat")));
Section 19.6
19.22 What types of objects can be stored using the
ObjectOutputStream? What is
the method for writing an object? What is the method for
reading an object? What
is the return type of the method that reads an object from
ObjectInputStream?
19.23 If you serialize two objects of the same type, will they
take the same amount of
space? If not, give an example.
19.24 Is it true that any instance of java.io.Serializable can be
successfully seri-
alized? Are the static variables in an object serialized? How do
you mark an
instance variable not to be serialized?
19.25 Can you write an array to an ObjectOutputStream?
19.26 Is it true that DataInputStream/DataOutputStream can
always be replaced
by ObjectInputStream/ObjectOutputStream?
19.27 What will happen when you attempt to run the following
code?
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
ObjectOutputStream output =
new ObjectOutputStream(new FileOutputStream("object.dat"));
output.writeObject(new A());
}
}
class A implements Serializable {
B b = new B();
}
class B {
}
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
671
672 Chapter 19 Binary I/O
Section 19.7
19.28 Can RandomAccessFile streams read and write a data file
created by
DataOutputStream? Can RandomAccessFile streams read and
write objects?
19.29 Create a RandomAccessFile stream for the file
address.dat to allow the updat-
ing of student information in the file. Create a
DataOutputStream for the file
address.dat. Explain the differences between these two
statements.
19.30 What happens if the file test.dat does not exist when you
attempt to compile and
run the following code?
import java.io.*;
public class Test {
public static void main(String[] args) {
try {
RandomAccessFile raf =
new RandomAccessFile("test.dat", "r");
int i = raf.readInt();
}
catch (IOException ex) {
System.out.println("IO exception");
}
}
}
PROGRAMMING EXERCISES
Section 19.3
19.1* (Creating a text file) Write a program to create a file
named Exercise19_1.txt if it
does not exist. Append new data to it. Write 100 integers
created randomly into the
file using text I/O. Integers are separated by a space.
Section 19.4
19.2* (Creating a binary data file) Write a program to create a
file named
Exercise19_2.dat if it does not exist. Append new data to it.
Write 100 integers
created randomly into the file using binary I/O.
19.3* (Summing all the integers in a binary data file) Suppose a
binary data file named
Exercise19_3.dat has been created using writeInt(int) in
DataOutput-
Stream. The file contains an unspecified number of integers.
Write a program to
find the sum of integers.
19.4* (Converting a text file into UTF) Write a program that
reads lines of characters from
a text and writes each line as a UTF-8 string into a binary file.
Display the sizes of
the text file and the binary file. Use the following command to
run the program:
java Exercise19_4 Welcome.java Welcome.utf
Section 19.6
19.5* (Storing objects and arrays into a file) Write a program
that stores an array of five
int values 1, 2, 3, 4 and 5, a Date object for current time, and a
double value 5.5
into the file named Exercise19_5.dat.
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
672
Programming Exercises 673
FIGURE 19.18 The application can store, retrieve, and update
addresses from a file.
(a) (b)
FIGURE 19.19 (a) The program splits a file. (b) The program
combines files into a new file.
19.6* (Storing Loan objects) The Loan class, in Listing 10.2,
does not implement
Serializable. Rewrite the Loan class to implement Serializable.
Write a
program that creates five Loan objects and stores them in a file
named
Exercise19_6.dat.
19.7* (Restoring objects from a file) Suppose a file named
Exercise19_7.dat has
been created using the ObjectOutputStream. The file contains
Loan
objects. The Loan class, in Listing 10.2, does not implement
Serializable.
Rewrite the Loan class to implement Serializable. Write a
program that
reads the Loan objects from the file and computes the total loan
amount. Sup-
pose you don’t know how many Loan objects are in the file. Use
EOFException to end the loop.
Section 19.7
19.8* (Updating count) Suppose you want to track how many
times a program has
been executed. You may store an int to count the file. Increase
the count by 1
each time this program is executed. Let the program be
Exercise19_8 and store
the count in Exercise19_8.dat.
19.9*** (Address book) Supplement VII.B gives a case study of
using random-access
files for creating and manipulating an address book. Modify the
case study by
adding an Update button, as shown in Figure 19.18, to enable
the user to modify
the address that is being displayed.
Comprehensive
19.10* (Splitting files) Suppose you wish to back up a huge file
(e.g., a 10-GB AVI file)
to a CD-R. You can achieve it by splitting the file into smaller
pieces and back-
ing up these pieces separately. Write a utility program that
splits a large file into
smaller ones using the following command:
java Exercise19_10 SourceFile numberOfPieces
The command creates files SourceFile.1, SourceFile.2,
SourceFile.n,
where n is numberOfPieces and the output files are about the
same size.
19.11** (Splitting files GUI) Rewrite Exercise 19.10 with a
GUI, as shown in Figure
19.19(a).
Á ,
Video Note
Split a large file
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
673
674 Chapter 19 Binary I/O
BitOutputStream
+BitOutputStream(file: File)
+writeBit(char bit): void
+writeBit(String bit): void
+close(): void
Creates a BitOutputStream to write bit to the file.
Write a bit '0' or '1' to the output stream.
Write a string of bits to the output stream.
This method must be invoked to close the stream.
FIGURE 19.20 BitOutputStream outputs a stream of bits to a
file.
19.12* (Combining files) Write a utility program that combines
the files together into a
new file using the following command:
java Exercise19_12 SourceFile1 SoureFilen TargetFile
The command combines SourceFile1, and SourceFilen into
TargetFile.
19.13* (Combining files GUI) Rewrite Exercise 19.12 with a
GUI, as shown in Figure
19.19(b).
19.14 (Encrypting files) Encode the file by adding 5 to every
byte in the file. Write a
program that prompts the user to enter an input file name and an
output file
name and saves the encrypted version of the input file to the
output file.
19.15 (Decrypting files) Suppose a file is encrypted using the
scheme in Exercise
19.14. Write a program to decode an encrypted file. Your
program should
prompt the user to enter an input file name and an output file
name and should
save the unencrypted version of the input file to the output file.
19.16 (Frequency of characters) Write a program that prompts
the user to enter the
name of an ASCII text file and display the frequency of the
characters in the file.
19.17** (BitOutputStream) Implement a class named
BitOutputStream, as shown
in Figure 19.20, for writing bits to an output stream. The
writeBit(char
bit) method stores the bit in a byte variable. When you create a
BitOutputStream, the byte is empty. After invoking
writeBit('1'), the
byte becomes 00000001. After invoking writeBit("0101"), the
byte
becomes 00010101. The first three bits are not filled yet. When
a byte is full, it
is sent to the output stream. Now the byte is reset to empty. You
must close the
stream by invoking the close() method. If the byte is not empty
and not full,
the close() method first fills the zeros to make a full 8 bits in
the byte, and
then output the byte and close the stream. For a hint, see
Exercise 4.46. Write a
test program that sends the bits 010000100100001001101 to the
file named
Exercise19_17.dat.
Á ,
Á
19.18* (View bits) Write the following method that displays the
bit representation for
the last byte in an integer:
public static String getBits(int value)
For a hint, see Exercise 4.46. Write a program that prompts the
user to enter a
file name, reads bytes from a file, and displays each byte’s
binary
representation.
19.19* (View hex) Write a program that prompts the user to
enter a file name, reads
bytes from a file, and displays each byte’s hex representation.
(Hint: You may
first convert the byte value into an 8-bit string, then convert the
bit string into a
two-digit hex string.)
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
674
Programming Exercises 675
(a) (b)
FIGURE 19.21 The exercises enable the user to manipulate the
contents of the file in binary and hex.
19.20** (Binary Editor) Write a GUI application that lets the
user enter a file name in the
text field and press the Enter key to display its binary
representation in a text
area. The user can also modify the binary code and save it back
to the file, as
shown in Figure 19.21(a).
19.21** (Hex Editor) Write a GUI application that lets the user
enter a file name in the
text field and press the Enter key to display its hex
representation in a text area.
The user can also modify the hex code and save it back to the
file, as shown in
Figure 19.21(b).
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
675
M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
676
1
Chapter 17 Binary I/O
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
2
Motivations
Data stored in a text file is represented in human-readable form.
Data stored in a binary file is represented in binary form. You
cannot read binary files. They are designed to be read by
programs. For example, Java source programs are stored in text
files and can be read by a text editor, but Java classes are stored
in binary files and are read by the JVM. The advantage of
binary files is that they are more efficient to process than text
files.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
3
Objectives
To discover how I/O is processed in Java (§17.2).
To distinguish between text I/O and binary I/O (§17.3).
To read and write bytes using FileInputStream and
FileOutputStream (§17.4.1).
To read and write primitive values and strings using
DataInputStream/DataOutputStream (§17.4.3).
To store and restore objects using ObjectOutputStream and
ObjectInputStream, and to understand how objects are serialized
and what kind of objects can be serialized (§17.6).
To implement the Serializable interface to make objects
serializable (§17.6.1).
To serialize arrays (§17.6.2).
To read and write the same file using the RandomAccessFile
class (§17.7).
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
4
How is I/O Handled in Java?
A File object encapsulates the properties of a file or a path, but
does not contain the methods for reading/writing data from/to a
file. In order to perform I/O, you need to create objects using
appropriate Java I/O classes.
PrintWriter output = new PrintWriter("temp.txt");
output.println("Java 101");
output.close();
Scanner input = new Scanner(new File("temp.txt"));
System.out.println(input.nextLine());
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
5
Text File vs. Binary File
Data stored in a text file are represented in human-readable
form. Data stored in a binary file are represented in binary
form. You cannot read binary files. Binary files are designed to
be read by programs. For example, the Java source programs are
stored in text files and can be read by a text editor, but the Java
classes are stored in binary files and are read by the JVM. The
advantage of binary files is that they are more efficient to
process than text files.
Although it is not technically precise and correct, you can
imagine that a text file consists of a sequence of characters and
a binary file consists of a sequence of bits. For example, the
decimal integer 199 is stored as the sequence of three
characters: '1', '9', '9' in a text file and the same integer is stored
as a byte-type value C7 in a binary file, because decimal 199
equals to hex C7.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
6
Binary I/O
Text I/O requires encoding and decoding. The JVM converts a
Unicode to a file specific encoding when writing a character
and coverts a file specific encoding to a Unicode when reading
a character. Binary I/O does not require conversions. When you
write a byte to a file, the original byte is copied into the file.
When you read a byte from a file, the exact byte in the file is
returned.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
7
Binary I/O Classes
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
8
The value returned is a byte as an int type.
InputStream
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
9
The value is a byte as an int type.
OutputStream
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
10
FileInputStream/FileOutputStream
FileInputStream/FileOutputStream associates a binary
input/output stream with an external file. All the methods in
FileInputStream/FileOuptputStream are inherited from its
superclasses.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
11
FileInputStream
To construct a FileInputStream, use the following constructors:
public FileInputStream(String filename)
public FileInputStream(File file)
A java.io.FileNotFoundException would occur if you attempt to
create a FileInputStream with a nonexistent file.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
12
FileOutputStream
To construct a FileOutputStream, use the following
constructors:
public FileOutputStream(String filename)
public FileOutputStream(File file)
public FileOutputStream(String filename, boolean append)
public FileOutputStream(File file, boolean append)
If the file does not exist, a new file would be created. If the file
already exists, the first two constructors would delete the
current contents in the file. To retain the current content and
append new data into the file, use the last two constructors by
passing true to the append parameter.
TestFileStream
Run
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
13
FilterInputStream/FilterOutputStream
Filter streams are streams that filter bytes for some purpose.
The basic byte input stream provides a read method that can
only be used for reading bytes. If you want to read integers,
doubles, or strings, you need a filter class to wrap the byte input
stream. Using a filter class enables you to read integers,
doubles, and strings instead of bytes and characters.
FilterInputStream and FilterOutputStream are the base classes
for filtering data. When you need to process primitive numeric
types, use DatInputStream and DataOutputStream to filter bytes.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
14
DataInputStream/DataOutputStream
DataInputStream reads bytes from the stream and converts them
into appropriate primitive type values or strings.
DataOutputStream converts primitive type values or strings into
bytes and output the bytes to the stream.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
15
DataInputStream
DataInputStream extends FilterInputStream and implements the
DataInput interface.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
16
DataOutputStream
DataOutputStream extends FilterOutputStream and implements
the DataOutput interface.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
17
Characters and Strings in Binary I/O
A Unicode consists of two bytes. The writeChar(char c) method
writes the Unicode of character c to the output. The
writeChars(String s) method writes the Unicode for each
character in the string s to the output.
Why UTF-8? What is UTF-8?
UTF-8 is a coding scheme that allows systems to operate with
both ASCII and Unicode efficiently. Most operating systems use
ASCII. Java uses Unicode. The ASCII character set is a subset
of the Unicode character set. Since most applications need only
the ASCII character set, it is a waste to represent an 8-bit ASCII
character as a 16-bit Unicode character. The UTF-8 is an
alternative scheme that stores a character using 1, 2, or 3 bytes.
ASCII values (less than 0x7F) are coded in one byte. Unicode
values less than 0x7FF are coded in two bytes. Other Unicode
values are coded in three bytes.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
18
Using DataInputStream/DataOutputStream
Data streams are used as wrappers on existing input and output
streams to filter data in the original stream. They are created
using the following constructors:
public DataInputStream(InputStream instream)
public DataOutputStream(OutputStream outstream)
The statements given below create data streams. The first
statement creates an input stream for file in.dat; the second
statement creates an output stream for file out.dat.
DataInputStream infile =
new DataInputStream(new FileInputStream("in.dat"));
DataOutputStream outfile =
new DataOutputStream(new FileOutputStream("out.dat"));
TestDataStream
Run
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
19
Checking End of File
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.
Order and Format
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.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
20
BufferedInputStream/
BufferedOutputStream
Using buffers to speed up I/O
BufferedInputStream/BufferedOutputStream does not contain
new methods. All the methods
BufferedInputStream/BufferedOutputStream are inherited from
the InputStream/OutputStream classes.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
21
Concept of pipe line
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
22
Constructing BufferedInputStream/BufferedOutputStream
// Create a BufferedInputStream
public BufferedInputStream(InputStream in)
public BufferedInputStream(InputStream in, int bufferSize)
// Create a BufferedOutputStream
public BufferedOutputStream(OutputStream out)
public BufferedOutputStream(OutputStreamr out, int
bufferSize)
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
23
Case Studies: Copy File
This case study develops a program that copies files. The user
needs to provide a source file and a target file as command-line
arguments using the following command:
java Copy source target
The program copies a source file to a target file and displays the
number of bytes in the file. If the source does not exist, tell the
user the file is not found. If the target file already exists, tell
the user the file already exists.
Copy
Run
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
24
Object I/O
DataInputStream/DataOutputStream enables you to perform I/O
for primitive type values and strings.
ObjectInputStream/ObjectOutputStream enables you to perform
I/O for objects in addition for primitive type values and strings.
Optional
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
25
ObjectInputStream
ObjectInputStream extends InputStream and implements
ObjectInput and ObjectStreamConstants.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
26
ObjectOutputStream
ObjectOutputStream extends OutputStream and implements
ObjectOutput and ObjectStreamConstants.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
27
Using Object Streams
You may wrap an ObjectInputStream/ObjectOutputStream on
any InputStream/OutputStream using the following
constructors:
// Create an ObjectInputStream
public ObjectInputStream(InputStream in)
// Create an ObjectOutputStream
public ObjectOutputStream(OutputStream out)
TestObjectOutputStream
Run
TestObjectInputStream
Run
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
28
The Serializable Interface
Not all objects can be written to an output stream. Objects that
can be written to an object stream is said to be serializable. A
serializable object is an instance of the java.io.Serializable
interface. So the class of a serializable object must implement
Serializable.
The Serializable interface is a marker interface. It has no
methods, so you don't need to add additional code in your class
that implements Serializable.
Implementing this interface enables the Java serialization
mechanism to automate the process of storing the objects and
arrays.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
29
The transient Keyword
If an object is an instance of Serializable, but it contains non-
serializable instance data fields, can the object be serialized?
The answer is no. To enable the object to be serialized, you can
use the transient keyword to mark these data fields to tell the
JVM to ignore these fields when writing the object to an object
stream.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
30
The transient Keyword, cont.
Consider the following class:
public class Foo implements java.io.Serializable {
private int v1;
private static double v2;
private transient A v3 = new A();
}
class A { } // A is not serializable
When an object of the Foo class is serialized, only variable v1
is serialized. Variable v2 is not serialized because it is a static
variable, and variable v3 is not serialized because it is marked
transient. If v3 were not marked transient, a
java.io.NotSerializableException would occur.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
31
Serializing Arrays
An array is serializable if all its elements are serializable. So an
entire array can be saved using writeObject into a file and later
restored using readObject. Here is an example that stores an
array of five int values and an array of three strings, and reads
them back to display on the console.
TestObjectStreamForArray
Run
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
32
Random Access Files
All of the streams you have used so far are known as read-only
or write-only streams. The external files of these streams are
sequential files that cannot be updated without creating a new
file. It is often necessary to modify files or to insert new
records into files. Java provides the RandomAccessFile class to
allow a file to be read from and write to at random locations.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
33
RandomAccessFile
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
34
File Pointer
A random access file consists of a sequence of bytes. There is a
special marker called file pointer that is positioned at one of
these bytes. A read or write operation takes place at the location
of the file pointer. When a file is opened, the file pointer sets at
the beginning of the file. When you read or write data to the
file, the file pointer moves forward to the next data. For
example, if you read an int value using readInt(), the JVM reads
four bytes from the file pointer and now the file pointer is four
bytes ahead of the previous location.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
35
RandomAccessFile Methods
Many methods in RandomAccessFile are the same as those in
DataInputStream and DataOutputStream. For example,
readInt(), readLong(), writeDouble(), readLine(), writeInt(),
and writeLong() can be used in data input stream or data output
stream as well as in RandomAccessFile streams.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
36
RandomAccessFile Methods, cont.
void seek(long pos) throws IOException;
Sets the offset from the beginning of the
RandomAccessFile stream to where the next read
or write occurs.
long getFilePointer() IOException;
Returns the current offset, in bytes, from the
beginning of the file to where the next read
or write occurs.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
37
RandomAccessFile Methods, cont.
long length()IOException
Returns the length of the file.
final void writeChar(int v) throws IOException
Writes a character to the file as a two-byte Unicode, with
the high byte written first.
final void writeChars(String s)
throws IOException
Writes a string to the file as a sequence of
characters.
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
38
RandomAccessFile Constructor
RandomAccessFile raf =
new RandomAccessFile("test.dat", "rw"); // allows read and
write
RandomAccessFile raf =
new RandomAccessFile("test.dat", "r"); // read only
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
39
A Short Example on RandomAccessFile
Run
TestRandomAccessFile
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
40
Case Studies: Address Book
Now let us use RandomAccessFile to create a useful project for
storing and viewing and address book. The Add button stores a
new address to the end of the file. The First, Next, Previous,
and Last buttons retrieve the first, next, previous, and last
addresses from the file, respectively.
Companion Website
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
41
Fixed Length String I/O
Random access files are often used to process files of records.
For convenience, fixed-length records are used in random
access files so that a record can be located easily. A record
consists of a fixed number of fields. A field can be a string or a
primitive data type. A string in a fixed-length record has a
maximum size. If a string is smaller than the maximum size, the
rest of the string is padded with blanks.
FixedLengthStringIO
Companion Website
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
42
Address Implementation
The rest of the work can be summarized in the following steps:
Create the user interface.
Add a record to the file.
Read a record from the file.
Write the code to implement the button actions.
Run
AddressBook
Companion Website
Liang, Introduction to Java Programming, Tenth Edition, (c)
2013 Pearson Education, Inc. All rights reserved.
Program
Input object
created from an
input class
Output object
created from an
output class
Input stream
Output stream
File
File
01011…1001
11001…1011
Program
Input object
created from an input class
File
Output object
created from an output class
01011…1001
File
Input stream
Output stream
11001…1011
java.io.InputStream
+read(): int
+read(b: byte[]): int
+read(b: byte[], off: int,
len: int): int
+available(): int
+close(): void
+skip(n: long): long
+markSupported(): boolean
+mark(readlimit: int): void
+reset(): void
Reads the next byte of d
ata from the input stream. The value byte is returned as
an int value in the range 0 to 255. If no byte is available
because the end of
the stream has been reached, the value
–
1 is returned.
Reads up to b.length bytes into array b from the input stream
and
returns the
actual number of bytes read. Returns
-
1 at the end of the stream.
Reads bytes from the input stream and stores into b[off],
b[off+1], …,
b[off+len
-
1]. The actual number of bytes read is returned. Returns
-
1 at the
end of the stream.
Returns
the number of bytes that can be read from the input stream.
Closes this input stream and releases any system resources
associated with the
stream.
Skips over and discards n bytes of data from this input stream.
The actual
number of bytes skipped is returne
d.
Tests if this input stream supports the mark and reset methods.
Marks the current position in this input stream.
Repositions this stream to the position at the time the mark
method was last
called on this input stream.
java.io.InputStream
+read(): int
+read(b: byte[]): int
+read(b: byte[], off: int, len: int): int
+available(): int
+close(): void
+skip(n: long): long
+markSupported(): boolean
+mark(readlimit: int): void
+reset(): void
Reads the next byte of data from the input stream. The value
byte is returned as an int value in the range 0 to 255. If no byte
is available because the end of the stream has been reached, the
value –1 is returned.
Reads up to b.length bytes into array b from the input stream
and returns the actual number of bytes read. Returns -1 at the
end of the stream.
Reads bytes from the input stream and stores into b[off],
b[off+1], …, b[off+len-1]. The actual number of bytes read is
returned. Returns -1 at the end of the stream.
Returns the number of bytes that can be read from the input
stream.
Closes this input stream and releases any system resources
associated with the stream.
Skips over and discards n bytes of data from this input stream.
The actual number of bytes skipped is returned.
Tests if this input stream supports the mark and reset methods.
Marks the current position in this input stream.
Repositions this stream to the position at the time the mark
method was last called on this input stream.
java.io.OutputStream
+write(int b): void
+write(b: byte[]): void
+write(b: byte[], off: int,
len: int): void
+close(): void
+flush(): void
Writes the specified byte to this output stream. The parameter b
is an int value.
(byte)b is written to th
e output stream.
Writes all the bytes in array b to the output stream.
Writes b[off], b[off+1], …, b[off+len
-
1] into the output stream.
Closes this output stream and releases any system resources
associated with the
stream.
Flushes this output stream and
forces any buffered output bytes to be written out.
java.io.OutputStream
+write(int b): void
+write(b: byte[]): void
+write(b: byte[], off: int, len: int): void
+close(): void
+flush(): void
Writes the specified byte to this output stream. The parameter b
is an int value. (byte)b is written to the output stream.
Writes all the bytes in array b to the output stream.
Writes b[off], b[off+1], …, b[off+len-1] into the output stream.
Closes this output stream and releases any system resources
associated with the stream.
Flushes this output stream and forces any buffered output bytes
to be written out.
InputStream
OutputStream
Object
ObjectOutputSt
ream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
FileInputStream
FilterInputStream
ObjectInputStream
PrintStream
DataOutputStream
BufferedOutputStream
DataInputStream
BufferedInputStream
FileOutputStream
FilterOutputStream
ObjectOutputStream
Object
OutputStream
InputStream
InputStream
OutputStream
Object
ObjectOutputSt
ream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
FileInputStream
FilterInputStream
ObjectInputStream
PrintStream
DataOutputStream
BufferedOutputStream
DataInputStream
BufferedInputStream
FileOutputStream
FilterOutputStream
ObjectOutputStream
Object
OutputStream
InputStream
InputStream
OutputStream
Object
ObjectOutputSt
ream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
FileInputStream
FilterInputStream
ObjectInputStream
PrintStream
DataOutputStream
BufferedOutputStream
DataInputStream
BufferedInputStream
FileOutputStream
FilterOutputStream
ObjectOutputStream
Object
OutputStream
InputStream
InputStream
OutputStream
Object
ObjectOutputSt
ream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
FileInputStream
FilterInputStream
ObjectInputStream
PrintStream
DataOutputStream
BufferedOutputStream
DataInputStream
BufferedInputStream
FileOutputStream
FilterOutputStream
ObjectOutputStream
Object
OutputStream
InputStream
DataInputStream
FileInputStream
External File
01000110011 …
int, double, string …
DataOutputStream
FileOutputStream
External File
01000110011 …
int, double, string …
FileInputStream
int, double, string …
01000110011 …
External File
FileOutputStream
DataInputStream
DataOutputStream
int, double, string …
01000110011 …
External File
InputStream
OutputStream
Object
ObjectOutputSt
ream
FilterOutputStream
FileOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectInputStream
FilterInputStream
FileInputStream
FileInputStream
FilterInputStream
ObjectInputStream
PrintStream
DataOutputStream
BufferedOutputStream
DataInputStream
BufferedInputStream
FileOutputStream
FilterOutputStream
ObjectOutputStream
Object
OutputStream
InputStream
java.io.ObjectInput
+readObject(): Object
Reads an object.
java.io.InputStream
java.io.ObjectInputStream
+ObjectInputStream(in: InputStream)
java.io.DataInput
ObjectStreamConstants
java.io.InputStream
java.io.ObjectInput
+readObject(): Object
Reads an object.
java.io.DataInput
java.io.ObjectInputStream
+ObjectInputStream(in: InputStream)
ObjectStreamConstants
java.io.ObjectOutput
+writeObject(o: Object): void
Writes an object.
java.io.OutputStream
java.io.ObjectOutputStream
+ObjectOutputStream(out: OutputStream)
java.io.DataOutput
ObjectStreamConstants
java.io.OutputStream
java.io.ObjectOutput
+writeObject(o: Object): void
Writes an object.
java.io.DataOutput
java.io.ObjectOutputStream
+ObjectOutputStream(out: OutputStream)
ObjectStreamConstants
Record 1
Record 2
Record n
Field1 Field 2 … Field k
file
e.g.,
Student 1
Student 2
Student n
name street city state zip
Record n
Record 2
Field1 Field 2 … Field k
Record 1
file
e.g.,
name street city state zip
Student n
Student 2
Student 1

More Related Content

Similar to BINARY IOObjectivesCHAPTER 19■ To discover how IO .docx

Similar to BINARY IOObjectivesCHAPTER 19■ To discover how IO .docx (20)

IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
Cis 170 c ilab 7 of 7 sequential files
Cis 170 c ilab 7 of 7 sequential filesCis 170 c ilab 7 of 7 sequential files
Cis 170 c ilab 7 of 7 sequential files
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Basic of Javaio
Basic of JavaioBasic of Javaio
Basic of Javaio
 
1.26 File Input-Output in JAVA.pptx
1.26 File Input-Output in JAVA.pptx1.26 File Input-Output in JAVA.pptx
1.26 File Input-Output in JAVA.pptx
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handling
 
Managing console input
Managing console inputManaging console input
Managing console input
 
Java programming Chapter 4.pptx
Java programming Chapter 4.pptxJava programming Chapter 4.pptx
Java programming Chapter 4.pptx
 
Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
 
Chapter10
Chapter10Chapter10
Chapter10
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++
 

More from hartrobert670

BUS M02C – Managerial Accounting SLO Assessment project .docx
BUS M02C – Managerial Accounting SLO Assessment project .docxBUS M02C – Managerial Accounting SLO Assessment project .docx
BUS M02C – Managerial Accounting SLO Assessment project .docxhartrobert670
 
BUS 409 – Student Notes(Prerequisite BUS 310)COURSE DESCR.docx
BUS 409 – Student Notes(Prerequisite BUS 310)COURSE DESCR.docxBUS 409 – Student Notes(Prerequisite BUS 310)COURSE DESCR.docx
BUS 409 – Student Notes(Prerequisite BUS 310)COURSE DESCR.docxhartrobert670
 
BUS LAW2HRM Management Discussion boardDis.docx
BUS LAW2HRM Management Discussion boardDis.docxBUS LAW2HRM Management Discussion boardDis.docx
BUS LAW2HRM Management Discussion boardDis.docxhartrobert670
 
BUS 571 Compensation and BenefitsCompensation Strategy Project.docx
BUS 571 Compensation and BenefitsCompensation Strategy Project.docxBUS 571 Compensation and BenefitsCompensation Strategy Project.docx
BUS 571 Compensation and BenefitsCompensation Strategy Project.docxhartrobert670
 
BUS 475 – Business and Society© 2014 Strayer University. All Rig.docx
BUS 475 – Business and Society© 2014 Strayer University. All Rig.docxBUS 475 – Business and Society© 2014 Strayer University. All Rig.docx
BUS 475 – Business and Society© 2014 Strayer University. All Rig.docxhartrobert670
 
BUS 210 Exam Instructions.Please read the exam carefully and a.docx
BUS 210 Exam Instructions.Please read the exam carefully and a.docxBUS 210 Exam Instructions.Please read the exam carefully and a.docx
BUS 210 Exam Instructions.Please read the exam carefully and a.docxhartrobert670
 
BUS 137S Special Topics in Marketing (Services Marketing)Miwa Y..docx
BUS 137S Special Topics in Marketing (Services Marketing)Miwa Y..docxBUS 137S Special Topics in Marketing (Services Marketing)Miwa Y..docx
BUS 137S Special Topics in Marketing (Services Marketing)Miwa Y..docxhartrobert670
 
BUS 313 – Student NotesCOURSE DESCRIPTIONThis course intro.docx
BUS 313 – Student NotesCOURSE DESCRIPTIONThis course intro.docxBUS 313 – Student NotesCOURSE DESCRIPTIONThis course intro.docx
BUS 313 – Student NotesCOURSE DESCRIPTIONThis course intro.docxhartrobert670
 
BUS 1 Mini Exam – Chapters 05 – 10 40 Points S.docx
BUS 1 Mini Exam – Chapters 05 – 10 40 Points S.docxBUS 1 Mini Exam – Chapters 05 – 10 40 Points S.docx
BUS 1 Mini Exam – Chapters 05 – 10 40 Points S.docxhartrobert670
 
BullyingIntroductionBullying is defined as any for.docx
BullyingIntroductionBullying is defined as any for.docxBullyingIntroductionBullying is defined as any for.docx
BullyingIntroductionBullying is defined as any for.docxhartrobert670
 
BUS1001 - Integrated Business PerspectivesCourse SyllabusSch.docx
BUS1001 - Integrated Business PerspectivesCourse SyllabusSch.docxBUS1001 - Integrated Business PerspectivesCourse SyllabusSch.docx
BUS1001 - Integrated Business PerspectivesCourse SyllabusSch.docxhartrobert670
 
BUMP implementation in Java.docxThe project is to implemen.docx
BUMP implementation in Java.docxThe project is to implemen.docxBUMP implementation in Java.docxThe project is to implemen.docx
BUMP implementation in Java.docxThe project is to implemen.docxhartrobert670
 
BUS 303 Graduate School and Further Education PlanningRead and w.docx
BUS 303 Graduate School and Further Education PlanningRead and w.docxBUS 303 Graduate School and Further Education PlanningRead and w.docx
BUS 303 Graduate School and Further Education PlanningRead and w.docxhartrobert670
 
Bulletin Board Submission 10 Points. Due by Monday at 900 a.m..docx
Bulletin Board Submission 10 Points. Due by Monday at 900 a.m..docxBulletin Board Submission 10 Points. Due by Monday at 900 a.m..docx
Bulletin Board Submission 10 Points. Due by Monday at 900 a.m..docxhartrobert670
 
BUS 371Fall 2014Final Exam – Essay65 pointsDue Monda.docx
BUS 371Fall 2014Final Exam – Essay65 pointsDue  Monda.docxBUS 371Fall 2014Final Exam – Essay65 pointsDue  Monda.docx
BUS 371Fall 2014Final Exam – Essay65 pointsDue Monda.docxhartrobert670
 
Burn with Us Sacrificing Childhood in The Hunger GamesSus.docx
Burn with Us Sacrificing Childhood in The Hunger GamesSus.docxBurn with Us Sacrificing Childhood in The Hunger GamesSus.docx
Burn with Us Sacrificing Childhood in The Hunger GamesSus.docxhartrobert670
 
BUS 305 SOLUTIONS TOPRACTICE PROBLEMS EXAM 21) B2) B3.docx
BUS 305 SOLUTIONS TOPRACTICE PROBLEMS EXAM 21) B2) B3.docxBUS 305 SOLUTIONS TOPRACTICE PROBLEMS EXAM 21) B2) B3.docx
BUS 305 SOLUTIONS TOPRACTICE PROBLEMS EXAM 21) B2) B3.docxhartrobert670
 
Burgerville- Motivation Goals.Peer-reviewed articles.Here ar.docx
Burgerville- Motivation Goals.Peer-reviewed articles.Here ar.docxBurgerville- Motivation Goals.Peer-reviewed articles.Here ar.docx
Burgerville- Motivation Goals.Peer-reviewed articles.Here ar.docxhartrobert670
 
Bullying Bullying in Schools PaperName.docx
Bullying     Bullying in Schools PaperName.docxBullying     Bullying in Schools PaperName.docx
Bullying Bullying in Schools PaperName.docxhartrobert670
 
Building Design and Construction FIRE 1102 – Principle.docx
Building Design and Construction FIRE 1102 – Principle.docxBuilding Design and Construction FIRE 1102 – Principle.docx
Building Design and Construction FIRE 1102 – Principle.docxhartrobert670
 

More from hartrobert670 (20)

BUS M02C – Managerial Accounting SLO Assessment project .docx
BUS M02C – Managerial Accounting SLO Assessment project .docxBUS M02C – Managerial Accounting SLO Assessment project .docx
BUS M02C – Managerial Accounting SLO Assessment project .docx
 
BUS 409 – Student Notes(Prerequisite BUS 310)COURSE DESCR.docx
BUS 409 – Student Notes(Prerequisite BUS 310)COURSE DESCR.docxBUS 409 – Student Notes(Prerequisite BUS 310)COURSE DESCR.docx
BUS 409 – Student Notes(Prerequisite BUS 310)COURSE DESCR.docx
 
BUS LAW2HRM Management Discussion boardDis.docx
BUS LAW2HRM Management Discussion boardDis.docxBUS LAW2HRM Management Discussion boardDis.docx
BUS LAW2HRM Management Discussion boardDis.docx
 
BUS 571 Compensation and BenefitsCompensation Strategy Project.docx
BUS 571 Compensation and BenefitsCompensation Strategy Project.docxBUS 571 Compensation and BenefitsCompensation Strategy Project.docx
BUS 571 Compensation and BenefitsCompensation Strategy Project.docx
 
BUS 475 – Business and Society© 2014 Strayer University. All Rig.docx
BUS 475 – Business and Society© 2014 Strayer University. All Rig.docxBUS 475 – Business and Society© 2014 Strayer University. All Rig.docx
BUS 475 – Business and Society© 2014 Strayer University. All Rig.docx
 
BUS 210 Exam Instructions.Please read the exam carefully and a.docx
BUS 210 Exam Instructions.Please read the exam carefully and a.docxBUS 210 Exam Instructions.Please read the exam carefully and a.docx
BUS 210 Exam Instructions.Please read the exam carefully and a.docx
 
BUS 137S Special Topics in Marketing (Services Marketing)Miwa Y..docx
BUS 137S Special Topics in Marketing (Services Marketing)Miwa Y..docxBUS 137S Special Topics in Marketing (Services Marketing)Miwa Y..docx
BUS 137S Special Topics in Marketing (Services Marketing)Miwa Y..docx
 
BUS 313 – Student NotesCOURSE DESCRIPTIONThis course intro.docx
BUS 313 – Student NotesCOURSE DESCRIPTIONThis course intro.docxBUS 313 – Student NotesCOURSE DESCRIPTIONThis course intro.docx
BUS 313 – Student NotesCOURSE DESCRIPTIONThis course intro.docx
 
BUS 1 Mini Exam – Chapters 05 – 10 40 Points S.docx
BUS 1 Mini Exam – Chapters 05 – 10 40 Points S.docxBUS 1 Mini Exam – Chapters 05 – 10 40 Points S.docx
BUS 1 Mini Exam – Chapters 05 – 10 40 Points S.docx
 
BullyingIntroductionBullying is defined as any for.docx
BullyingIntroductionBullying is defined as any for.docxBullyingIntroductionBullying is defined as any for.docx
BullyingIntroductionBullying is defined as any for.docx
 
BUS1001 - Integrated Business PerspectivesCourse SyllabusSch.docx
BUS1001 - Integrated Business PerspectivesCourse SyllabusSch.docxBUS1001 - Integrated Business PerspectivesCourse SyllabusSch.docx
BUS1001 - Integrated Business PerspectivesCourse SyllabusSch.docx
 
BUMP implementation in Java.docxThe project is to implemen.docx
BUMP implementation in Java.docxThe project is to implemen.docxBUMP implementation in Java.docxThe project is to implemen.docx
BUMP implementation in Java.docxThe project is to implemen.docx
 
BUS 303 Graduate School and Further Education PlanningRead and w.docx
BUS 303 Graduate School and Further Education PlanningRead and w.docxBUS 303 Graduate School and Further Education PlanningRead and w.docx
BUS 303 Graduate School and Further Education PlanningRead and w.docx
 
Bulletin Board Submission 10 Points. Due by Monday at 900 a.m..docx
Bulletin Board Submission 10 Points. Due by Monday at 900 a.m..docxBulletin Board Submission 10 Points. Due by Monday at 900 a.m..docx
Bulletin Board Submission 10 Points. Due by Monday at 900 a.m..docx
 
BUS 371Fall 2014Final Exam – Essay65 pointsDue Monda.docx
BUS 371Fall 2014Final Exam – Essay65 pointsDue  Monda.docxBUS 371Fall 2014Final Exam – Essay65 pointsDue  Monda.docx
BUS 371Fall 2014Final Exam – Essay65 pointsDue Monda.docx
 
Burn with Us Sacrificing Childhood in The Hunger GamesSus.docx
Burn with Us Sacrificing Childhood in The Hunger GamesSus.docxBurn with Us Sacrificing Childhood in The Hunger GamesSus.docx
Burn with Us Sacrificing Childhood in The Hunger GamesSus.docx
 
BUS 305 SOLUTIONS TOPRACTICE PROBLEMS EXAM 21) B2) B3.docx
BUS 305 SOLUTIONS TOPRACTICE PROBLEMS EXAM 21) B2) B3.docxBUS 305 SOLUTIONS TOPRACTICE PROBLEMS EXAM 21) B2) B3.docx
BUS 305 SOLUTIONS TOPRACTICE PROBLEMS EXAM 21) B2) B3.docx
 
Burgerville- Motivation Goals.Peer-reviewed articles.Here ar.docx
Burgerville- Motivation Goals.Peer-reviewed articles.Here ar.docxBurgerville- Motivation Goals.Peer-reviewed articles.Here ar.docx
Burgerville- Motivation Goals.Peer-reviewed articles.Here ar.docx
 
Bullying Bullying in Schools PaperName.docx
Bullying     Bullying in Schools PaperName.docxBullying     Bullying in Schools PaperName.docx
Bullying Bullying in Schools PaperName.docx
 
Building Design and Construction FIRE 1102 – Principle.docx
Building Design and Construction FIRE 1102 – Principle.docxBuilding Design and Construction FIRE 1102 – Principle.docx
Building Design and Construction FIRE 1102 – Principle.docx
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfSanaAli374401
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 

Recently uploaded (20)

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 

BINARY IOObjectivesCHAPTER 19■ To discover how IO .docx

  • 1. BINARY I/O Objectives CHAPTER 19 ■ To discover how I/O is processed in Java (§19.2). ■ To distinguish between text I/O and binary I/O (§19.3). ■ To read and write bytes using FileInputStream and FileOutputStream (§19.4.1). ■ To filter data using base classes FilterInputStream/FilterOutputStream (§19.4.2). ■ To read and write primitive values and strings using DataInputStream/DataOutputStream (§19.4.3). ■ To store and restore objects using ObjectOutputStream and ObjectInputStream, and to understand how objects are serialized and what kind of objects can be serialized (§19.6). ■ To implement the Serializable interface to make objects serializable (§19.6.1). ■ To serialize arrays (§19.6.2). ■ To read and write files using the RandomAccessFile class (§19.7).
  • 2. M19_LIAN0807_08_SE_C19.QXD 11/24/09 10:52 AM Page 649 650 Chapter 19 Binary I/O 19.1 Introduction Data stored in a text file are represented in human-readable form. Data stored in a binary file are represented in binary form. You cannot read binary files. They are designed to be read by programs. For example, Java source programs are stored in text files and can be read by a text editor, but Java classes are stored in binary files and are read by the JVM. The advantage of binary files is that they are more efficient to process than text files. Although it is not technically precise and correct, you can envision a text file as consisting of a sequence of characters and a binary file as consisting of a sequence of bits. For example, the decimal integer 199 is stored as the sequence of three characters, '1', '9', '9', in a text file, and the same integer is stored as a byte-type value C7 in a binary file, because decimal 199 equals hex C7 Java offers many classes for performing file input and output. These can be categorized as text I/O classes and binary I/O classes. In §9.7, “File Input and Output,” you learned how to read/write strings and numeric values from/to a text file using Scanner and PrintWriter. This section introduces the classes for performing binary I/O.
  • 3. 19.2 How is I/O Handled in Java? Recall that a File object encapsulates the properties of a file or a path but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to cre- ate objects using appropriate Java I/O classes. The objects contain the methods for reading/writing data from/to a file. For example, to write text to a file named temp.txt, you may create an object using the PrintWriter class as follows: PrintWriter output = new PrintWriter("temp.txt"); You can now invoke the print method from the object to write a string into the file. For example, the following statement writes "Java 101" to the file. output.print("Java 101"); The next statement closes the file. output.close(); There are many I/O classes for various purposes. In general, these can be classified as input classes and output classes. An input class contains the methods to read data, and an output class contains the methods to write data. PrintWriter is an example of an output class, and Scanner is an example of an input class. The following code creates an input object for the file temp.txt and reads data from the file. Scanner input = new Scanner(new File("temp.txt")); System.out.println(input.nextLine());
  • 4. If temp.txt contains "Java 101", input.nextLine() returns string "Java 101". Figure 19.1 illustrates Java I/O programming. An input object reads a stream of data from a file, and an output object writes a stream of data to a file. An input object is also called an input stream and an output object an output stream. 19.3 Text I/O vs. Binary I/O Computers do not differentiate binary files and text files. All files are stored in binary format, and thus all files are essentially binary files. Text I/O is built upon binary I/O to provide a level of abstraction for character encoding and decoding, as shown in Figure 19.2(a). Encoding and decoding are automatically performed for text I/O. The JVM converts a Unicode to a file-specific 1199 = 12 * 161 + 72. text file binary file why binary I/O? text I/O binary I/O input stream output stream M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page
  • 5. 650 19.3 Text I/O vs. Binary I/O 651 Program Input object created from an input class Output object created from an output class Input stream 01011...1001 11001...1011 Output stream File File FIGURE 19.1 The program receives data through an input object and sends data through an output object. The same byte in the file
  • 6. The encoding of the character is stored in the file Binary I/O program Text I/O program The Unicode of the character Encoding/ Decoding A byte is read/written e.g., "199" e.g., 199 00110001 00111001 00111001 0x31 0xC7 0x39 0x39 00110111 (a) (b) FIGURE 19.2 Text I/O requires encoding and decoding, whereas binary I/O does not.
  • 7. encoding when writing a character and converts a file-specific encoding to a Unicode when reading a character. For example, suppose you write string "199" using text I/O to a file. Each character is written to the file. Since the Unicode for character '1' is 0x0031, the Unicode 0x0031 is converted to a code that depends on the encoding scheme for the file. (Note that the prefix 0x denotes a hex number.) In the United States, the default encoding for text files on Win- dows is ASCII. The ASCII code for character '1' is 49 (0x31 in hex) and for character '9' is 57 (0x39 in hex). So to write the characters "199", three bytes— 0x31, 0x39, and 0x39—are sent to the output, as shown in Figure 19.2(a). Note The new version of Java supports supplementary Unicode. For simplicity, however, this book con- siders only the original Unicode from 0 to FFFF. Binary I/O does not require conversions. If you write a numeric value to a file using binary I/O, the exact value in the memory is copied into the file. For example, a byte-type value 199 is represented as 0xC7 in the memory and appears exactly as 0xC7 in the file, as shown in Figure 19.2(b). When you read a byte using binary I/O, one byte value is read from the input. In general, you should use text input to read a file created by a text editor or a text output program, and use binary input to read a file created by a Java binary output program.
  • 8. 1199 = 12 * 161 + 72 supplementary Unicode M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 651 652 Chapter 19 Binary I/O FileOutputStream FilterOutputStream ObjectOutputStream FileInputStream OutputStream InputStream FilterInputStream ObjectInputStream Object DataInputStream BufferedInputStream DataOutputStream BufferedOutputStream FIGURE 19.3 InputStream, OutputStream, and their subclasses
  • 9. are for binary I/O. java.io.InputStream +read(): int +read(b: byte[]): int +read(b: byte[], off: int, len: int): int +available(): int +close(): void +skip(n: long): long +markSupported(): boolean +mark(readlimit: int): void +reset(): void Reads the next byte of data from the input stream. The value byte is returned as an int value in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value –1 is returned. Reads up to b.length bytes into array b from the input stream and returns the actual number of bytes read. Returns –1 at the end of the stream. Reads bytes from the input stream and stores them in b[off], b[off+1], . . ., b[off+len-1]. The actual number of bytes read is returned. Returns –1
  • 10. at the end of the stream. Returns an estimate of the number of bytes that can be read from the input stream. Closes this input stream and releases any system resources occupied by it. Skips over and discards n bytes of data from this input stream. The actual number of bytes skipped is returned. Tests whether this input stream supports the mark and reset methods. Marks the current position in this input stream. Repositions this stream to the position at the time the mark method was last called on this input stream. FIGURE 19.4 The abstract InputStream class defines the methods for the input stream of bytes. Binary I/O is more efficient than text I/O, because binary I/O does not require encoding and decoding. Binary files are independent of the encoding scheme on the host machine and thus are portable. Java programs on any machine can read a binary file created by a Java pro- gram. This is why Java class files are binary files. Java class files can run on a JVM on any machine. Note For consistency, this book uses the extension .txt to name text files and .dat to name binary
  • 11. files. 19.4 Binary I/O Classes The design of the Java I/O classes is a good example of applying inheritance, where common operations are generalized in superclasses, and subclasses provide specialized operations. Figure 19.3 lists some of the classes for performing binary I/O. InputStream is the root for binary input classes, and OutputStream is the root for binary output classes. Figures 19.4 and 19.5 list all the methods in InputStream and OutputStream. .txt and .dat M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 652 19.4 Binary I/O Classes 653 java.io.InputStream +FileInputStream(file: File) +FileInputStream(filename: String) javo.io.FileInputStream Creates a FileInputStream from a File object. Creates a FileInputStream from a file name. FIGURE 19.5 The abstract OutputStream class defines the methods for the output stream of bytes.
  • 12. Creates a FileOutputStream from a File object. Creates a FileOutputStream from a file name. If append is true, data are appended to the existing file. If append is true, data are appended to the existing file. java.io.OutputStream +FileOutputStream(file: File) +FileOutputStream(filename: String) +FileOutputStream(file: File, append: boolean) +FileOutputStream(filename: String, append: boolean) java.io.FileOutputStream FIGURE 19.6 FileInputStream inputs a stream of bytes from a file. FIGURE 19.7 FileOutputStream outputs a stream of bytes to a file. java.io.OutputStream +write(int b): void +write(b: byte[], off: int, len: int): void +write(b: byte[]): void +close(): void +flush(): void Writes the specified byte to this output stream. The parameter b is an int value.
  • 13. (byte)b is written to the output stream. Writes b[off], b[off+1],. . ., b[off+len-1] into the output stream. Writes all the bytes in array b to the output stream. Closes this output stream and releases any system resources occupied by it. Flushes this output stream and forces any buffered output bytes to be written out. throws IOException Note All the methods in the binary I/O classes are declared to throw java.io.IOException or a subclass of java.io.IOException. 19.4.1 FileInputStream/FileOutputStream FileInputStream/FileOutputStream is for reading/writing bytes from/to files. All the methods in these classes are inherited from InputStream and OutputStream. FileInputStream/FileOutputStream does not introduce new methods. To construct a FileInputStream, use the following constructors, as shown in Figure 19.6: FileNotFoundExceptionA java.io.FileNotFoundException will occur if you attempt to create a File- InputStream with a nonexistent file. To construct a FileOutputStream, use the constructors shown in Figure 19.7. If the file does not exist, a new file will be created. If the file
  • 14. already exists, the first two con- structors will delete the current content of the file. To retain the current content and append new data into the file, use the last two constructors by passing true to the append parameter. M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 653 654 Chapter 19 Binary I/O public static void main(String[] args) throws IOException { // Perform I/O operations } Declaring exception in the method public static void main(String[] args) { try { // Perform I/O operations } catch (IOException ex) { ex.printStackTrace(); } } Using try-catch block Almost all the methods in the I/O classes throw java.io.IOException. Therefore you have to declare java.io.IOException to throw in the method or place the code in a try- catch block, as shown below:
  • 15. IOException import output stream output input stream input 1 2 3 4 5 6 7 8 9 10 end of a file A FileOutputStream is created for file temp.dat in line 6. The for loop writes ten byte values into the file (lines 9–10). Invoking write(i) is the same as invoking write((byte)i). Line 13 closes the output stream. Line 16 creates a FileInputStream for file temp.dat. Values are read from the file and displayed on the console in lines 19–21. The expression ((value = input.read()) != -1) (line 20) reads a byte from input.read(), assigns it to value, and checks whether it is –1. The input value of –1 signifies the end of a file. Listing 19.1 uses binary I/O to write ten byte values from 1 to 10 to a file named temp.dat and reads them back from the file. LISTING 19.1 TestFileStream.java
  • 16. 1 import java.io.*; 2 3 public class TestFileStream { 4 public static void main(String[] args) { 5 // Create an output stream to the file 6 7 8 // Output values to the file 9 for (int i = 1; i <= 10; i++) 10 11 12 // Close the output stream 13 14 15 // Create an input stream for the file 16 17 18 // Read values from the file 19 int value; 20 while ((value = ) != -1) 21 System.out.print(value + " "); 22 23 // Close the output stream 24 25 } 26 } input.close(); input.read() FileInputStream input = new FileInputStream("temp.dat"); output.close();
  • 17. output.write(i); FileOutputStream output = new FileOutputStream("temp.dat"); throws IOException M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 654 19.4 Binary I/O Classes 655 FIGURE 19.8 A binary file cannot be displayed in text mode. Binary data The file temp.dat created in this example is a binary file. It can be read from a Java program but not from a text editor, as shown in Figure 19.8. Tip When a stream is no longer needed, always close it using the close() method. Not closing streams may cause data corruption in the output file, or other programming errors. Note The root directory for the file is the classpath directory. For the example in this book, the root directory is c:book. So the file temp.dat is located at c:book. If you wish to place temp.dat in a specific directory, replace line 8 by FileOutputStream output = new FileOutputStream("directory/temp.dat");
  • 18. Note An instance of FileInputStream can be used as an argument to construct a Scanner, and an instance of FileOutputStream can be used as an argument to construct a PrintWriter. You can create a PrintWriter to append text into a file using new PrintWriter(new FileOutputStream("temp.txt", true)); If temp.txt does not exist, it is created. If temp.txt already exists, new data are appended to the file. 19.4.2 FilterInputStream/FilterOutputStream Filter streams are streams that filter bytes for some purpose. The basic byte input stream pro- vides a read method that can be used only for reading bytes. If you want to read integers, doubles, or strings, you need a filter class to wrap the byte input stream. Using a filter class enables you to read integers, doubles, and strings instead of bytes and characters. FilterInputStream and FilterOutputStream are the base classes for filtering data. When you need to process primitive numeric types, use DataInputStream and DataOutputStream to filter bytes. 19.4.3 DataInputStream/DataOutputStream DataInputStream reads bytes from the stream and converts them into appropriate primitive type values or strings. DataOutputStream converts primitive type values or strings into bytes and outputs the bytes to the stream.
  • 19. DataInputStream extends FilterInputStream and implements the DataInput interface, as shown in Figure 19.9. DataOutputStream extends FilterOutputStream and implements the DataOutput interface, as shown in Figure 19.10. DataInputStream implements the methods defined in the DataInput interface to read primitive data type values and strings. DataOutputStream implements the methods defined in the DataOutput interface to write primitive data type values and strings. Primitive values close stream where is the file? appending to text file M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 655 656 Chapter 19 Binary I/O FIGURE 19.10 DataOutputStream enables you to write primitive data type values and strings into an output stream. +writeChar(c: char): void +writeChars(s: String): void +writeBoolean(b: boolean): void +writeByte(v: int): void
  • 20. +writeBytes(s: String): void +writeFloat(v: float): void +writeDouble(v: double): void +writeInt(v: int): void +writeLong(v: long): void +writeShort(v: short): void +writeUTF(s: String): void Writes a Boolean to the output stream. Writes the eight low-order bits of the argument v to the output stream. Writes the lower byte of the characters in a string to the output stream. Writes a character (composed of 2 bytes) to the output stream. Writes every character in the string s to the output stream, in order, 2 bytes per character. Writes a float value to the output stream. Writes a double value to the output stream. Writes an int value to the output stream. Writes a long value to the output stream.
  • 21. Writes a short value to the output stream. Writes s string in UTF format. OutputStream FilterOutputStream DataOutputStream +DataOutputStream (out: OutputStream) «interface» java.io.DataOutput are copied from memory to the output without any conversions. Characters in a string may be written in several ways, as discussed in the next section. Characters and Strings in Binary I/O A Unicode consists of two bytes. The writeChar(char c) method writes the Unicode of character c to the output. The writeChars(String s) method writes the Unicode for each character in the string s to the output. The writeBytes(String s) method writes the lower byte of the Unicode for each character in the string s to the output. The high byte of the Uni- code is discarded. The writeBytes method is suitable for strings that consist of ASCII char- acters, since an ASCII code is stored only in the lower byte of a Unicode. If a string consists of non-ASCII characters, you have to use the writeChars method to write the string.
  • 22. The writeUTF(String s) method writes two bytes of length information to the output stream, followed by the modified UTF-8 representation of every character in the string s. UTF-8 is a coding scheme that allows systems to operate with both ASCII and Unicode. Most operating systems use ASCII. Java uses Unicode. The ASCII character set is a subset of the Unicode character set. Since most applications need only the ASCII character set, it is a waste to represent an 8-bit ASCII character as a 16-bit Unicode character. The modified UTF-8 scheme stores a character using one, two, or three bytes. Characters are coded in one byte if +readBoolean(): boolean +readByte(): byte +readChar(): char +readFloat(): float +readDouble(): double +readInt(): int +readLong(): long +readShort(): short +readLine(): String +readUTF(): String Reads a Boolean from the input stream.
  • 23. Reads a byte from the input stream. Reads a character from the input stream. Reads a float from the input stream. Reads a double from the input stream. Reads an int from the input stream. Reads a long from the input stream. Reads a short from the input stream. Reads a line of characters from input. Reads a string in UTF format. InputStream FilterInputStream DataInputStream +DataInputStream( in: InputStream) «interface» java.io.DataInput FIGURE 19.9 DataInputStream filters an input stream of bytes into primitive data type values and strings. M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 656
  • 24. 19.4 Binary I/O Classes 657 their code is less than or equal to 0x7F, in two bytes if their code is greater than 0x7F and less than or equal to 0x7FF, or in three bytes if their code is greater than 0x7FF. The initial bits of a UTF-8 character indicate whether a character is stored in one byte, two bytes, or three bytes. If the first bit is 0, it is a one-byte character. If the first bits are 110, it is the first byte of a two-byte sequence. If the first bits are 1110, it is the first byte of a three-byte sequence. The information that indicates the number of characters in a string is stored in the first two bytes preceding the UTF-8 characters. For example, writeUTF("ABCDEF") actu- ally writes eight bytes (i.e., 00 06 41 42 43 44 45 46) to the file, because the first two bytes store the number of characters in the string. The writeUTF(String s) method converts a string into a series of bytes in the UTF-8 format and writes them into a binary stream. The readUTF() method reads a string that has been written using the writeUTF method. The UTF-8 format has the advantage of saving a byte for each ASCII character, because a Unicode character takes up two bytes and an ASCII character in UTF-8 only one byte. If most of the characters in a long string are regular ASCII characters, using UTF-8 is efficient.
  • 25. Using DataInputStream/DataOutputStream Data streams are used as wrappers on existing input, and output streams to filter data in the orig- inal stream. They are created using the following constructors (see Figures 19.9 and 19.10): public DataInputStream(InputStream instream) public DataOutputStream(OutputStream outstream) The statements given below create data streams. The first statement creates an input stream for file in.dat; the second statement creates an output stream for file out.dat. DataInputStream input = (new FileInputStream("in.dat")); DataOutputStream output = (new FileOutputStream("out.dat")); Listing 19.2 writes student names and scores to a file named temp.dat and reads the data back from the file. LISTING 19.2 TestDataStream.java 1 import java.io.*; 2 3 public class TestDataStream { 4 public static void main(String[] args) throws IOException { 5 // Create an output stream for file temp.dat 6 7 8 9 // Write student test scores to the file 10
  • 26. 11 12 output.writeUTF("Jim"); 13 output.writeDouble(185.5); 14 output.writeUTF("George"); 15 output.writeDouble(105.25); 16 17 // Close output stream 18 output.close(); 19 20 // Create an input stream for file temp.dat 21 22 23 new DataInputStream(new FileInputStream("temp.dat")); DataInputStream input = output.writeDouble(85.5); output.writeUTF("John"); new DataOutputStream(new FileOutputStream("temp.dat")); DataOutputStream output = new DataOutputStream new DataInputStream UTF-8 scheme output stream output close stream input stream
  • 27. M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 657 658 Chapter 19 Binary I/O input John 85.5 Jim 185.5 George 105.25 A DataOutputStream is created for file temp.dat in lines 6–7. Student names and scores are written to the file in lines 10–15. Line 18 closes the output stream. A DataInputStream is created for the same file in lines 21–22. Student names and scores are read back from the file and displayed on the console in lines 25–27. DataInputStream and DataOutputStream read and write Java primitive type values and strings in a machine-independent fashion, thereby enabling you to write a data file on one machine and read it on another machine that has a different operating system or file structure. An application uses a data output stream to write data that can later be read by a program using a data input stream. Caution You have to read data in the same order and format in which they are stored. For example, since names are written in UTF-8 using writeUTF, you must read
  • 28. names using readUTF. Detecting End of File If you keep reading data at the end of an InputStream, an EOFException will occur. This exception may be used to detect the end of file, as shown in Listing 19.3. LISTING 19.3 DetectEndOfFile.java 1 import java.io.*; 2 3 public class DetectEndOfFile { 4 public static void main(String[] args) { 5 try { 6 DataOutputStream output = new DataOutputStream 7 (new FileOutputStream("test.dat")); 8 output.writeDouble(4.5); 9 output.writeDouble(43.25); 10 output.writeDouble(3.2); 11 output.close(); 12 13 DataInputStream input = new DataInputStream 14 (new FileInputStream("test.dat")); 15 while (true) { 16 System.out.println( ); 17 } 18 } 19 20 System.out.println("All data read"); 21 } 22 catch (IOException ex) { 23 ex.printStackTrace(); 24 } 25 } 26 }
  • 29. catch (EOFException ex) { input.readDouble() EOFException output stream output close stream input stream input EOFException 24 // Read student test scores from the file 25 System.out.println( + " " + ); 26 System.out.println(input.readUTF() + " " + input.readDouble()); 27 System.out.println(input.readUTF() + " " + input.readDouble()); 28 } 29 } input.readDouble()input.readUTF() M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 658 19.4 Binary I/O Classes 659
  • 30. FIGURE 19.11 BufferedInputStream buffers input stream. 4.5 43.25 3.2 All data read Creates a BufferedInputStream from an InputStream object. Creates a BufferedInputStream from an InputStream object with specified buffer size. +BufferedInputStream(in: InputStream) +BufferedInputStream(filename: String, bufferSize: int) java.io.InputStream java.io.FilterInputStream java.io.BufferedInputStream The program writes three double values to the file using DataOutputStream (lines 6–10), and reads the data using DataInputStream (lines 13–17). When reading past the end of file, an EOFException is thrown. The exception is caught in line 19. 19.4.4 BufferedInputStream/BufferedOutputStream BufferedInputStream/BufferedOutputStream can be used to speed up input and output by reducing the number of reads and writes. BufferedInputStream/ BufferedOutputStream does not contain new methods. All the methods in
  • 31. BufferedInputStream/BufferedOutputStream are inherited from the InputStream/ OutputStream classes. BufferedInputStream/BufferedOutputStream adds a buffer in the stream for storing bytes for efficient processing. You may wrap a BufferedInputStream/BufferedOutputStream on any InputStream/OutputStream using the constructors shown in Figures 19.11 and 19.12. Creates a BufferedOutputStream from an OutputStream object. Creates a BufferedOutputStream from an OutputStream object with specified size. +BufferedOutputStream(out: OutputStream) +BufferedOutputStream(filename: String, bufferSize: int) java.io.OutputStream java.io.FilterOutputStream java.io.BufferedOutputStream FIGURE 19.12 BufferedOutputStream buffers output stream. M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 659 660 Chapter 19 Binary I/O
  • 32. File exists Delete file Copy Source does not exist FIGURE 19.13 The program copies a file. If no buffer size is specified, the default size is 512 bytes. A buffered input stream reads as many data as possible into its buffer in a single read call. By contrast, a buffered output stream calls the write method only when its buffer fills up or when the flush() method is called. You can improve the performance of the TestDataStream program in the preceding example by adding buffers in the stream in lines 6–7 and 13–14 as follows: DataOutputStream output = new DataOutputStream( (new FileOutputStream("temp.dat"))); DataInputStream input = new DataInputStream( (new FileInputStream("temp.dat"))); Tip You should always use buffered IO to speed up input and output. For small files, you may not notice performance improvements. However, for large files— over 100 MB—you will see substan- tial improvements using buffered IO.
  • 33. 19.5 Problem: Copying Files This section develops a program that copies files. The user needs to provide a source file and a target file as command-line arguments using the following command: java Copy source target The program copies a source file to a target file and displays the number of bytes in the file. If the source does not exist, the user is told that the file has not been found. If the target file already exists, the user is told that the file exists. A sample run of the program is shown in Figure 19.13. new BufferedInputStream new BufferedOutputStream To copy the contents from a source to a target file, it is appropriate to use a binary input stream to read bytes from the source file and a binary output stream to send bytes to the target file, regardless of the contents of the file. The source file and the target file are specified from the command line. Create an InputFileStream for the source file and an OutputFileStream for the target file. Use the read() method to read a byte from the input stream, and then use the write(b) method to write the byte to the output stream. Use BufferedInputStream and BufferedOutputStream to improve the performance. Listing 19.4 gives the solution to the problem.
  • 34. Video Note Copy file M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 660 19.5 Problem: Copying Files 661 LISTING 19.4 Copy.java 1 import java.io.*; 2 3 public class Copy { 4 /** Main method 5 @param args[0] for sourcefile 6 @param args[1] for target file 7 */ 8 public static void main(String[] args) throws IOException { 9 // Check command-line parameter usage 10 if (args.length != 2) { 11 System.out.println( 12 "Usage: java Copy sourceFile targetfile"); 13 System.exit(0); 14 } 15 16 // Check whether source file exists 17 18 if (!sourceFile.exists()) { 19 System.out.println("Source file " + args[0] + " not exist"); 20 System.exit(0); 21 } 22 23 // Check whether target file exists 24
  • 35. 25 if (targetFile.exists()) { 26 System.out.println("Target file " + args[1] + " already 27 exists"); 28 System.exit(0); 29 } 30 31 // Create an input stream 32 33 34 35 // Create an output stream 36 37 38 39 // Continuously read a byte from input and write it to output 40 int r; int numberOfBytesCopied = 0; 41 while (( ) != -1) { 42 43 numberOfBytesCopied++; 44 } 45 46 // Close streams 47 input.close(); 48 output.close(); 49 50 // Display the file size 51 System.out.println(numberOfBytesCopied + " bytes copied"); 52 } 53 } The program first checks whether the user has passed two required arguments from the com- mand line in lines 10–14.
  • 36. The program uses the File class to check whether the source file and target file exist. If the source file does not exist (lines 18–21) or if the target file already exists, exit the program. output.write((byte)r); r = input.read() new BufferedOutputStream(new FileOutputStream(targetFile)); BufferedOutputStream output = new BufferedInputStream(new FileInputStream(sourceFile)); BufferedInputStream input = File targetFile = new File(args[1]); File sourceFile = new File(args[0]); check usage source file target file input stream output stream read write close stream M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 661
  • 37. 662 Chapter 19 Binary I/O Reads an object. java.io.InputStream java.io.ObjectInputStream +ObjectInputStream(in: InputStream) +readObject(): Object «interface» java.io.DataInput «interface» java.io.ObjectInput «interface» ObjectStreamConstants FIGURE 19.14 ObjectInputStream can read objects, primitive type values, and strings. Writes an object. java.io.OutputStream java.io.ObjectOutputStream +ObjectOutputStream(out: OutputStream) +writeObject(o: Object): void «interface» java.io.DataOutput
  • 38. «interface» java.io.ObjectOutput «interface» ObjectStreamConstants FIGURE 19.15 ObjectOutputStream can write objects, primitive type values, and strings. An input stream is created using BufferedInputStream wrapped on FileInputStream in lines 32–33, and an output stream is created using BufferedOutputStream wrapped on FileOutputStream in lines 36–37. The expression ((r = input.read()) != -1) (line 41) reads a byte from input. read(), assigns it to r, and checks whether it is –1. The input value of –1 signifies the end of a file. The program continuously reads bytes from the input stream and sends them to the out- put stream until all of the bytes have been read. 19.6 Object I/O DataInputStream/DataOutputStream enables you to perform I/O for primitive type values and strings. ObjectInputStream/ObjectOutputStream enables you to perform I/O for objects in addition to primitive type values and strings. Since ObjectInputStream/ ObjectOutputStream contains all the functions of DataInputStream/ DataOutputStream, you can replace DataInputStream/DataOutputStream com- pletely with ObjectInputStream/ObjectOutputStream.
  • 39. ObjectInputStream extends InputStream and implements ObjectInput and ObjectStreamConstants, as shown in Figure 19.14. ObjectInput is a subinterface of DataInput. DataInput is shown in Figure 19.9. ObjectStreamConstants contains the constants to support ObjectInputStream/ObjectOutputStream. ObjectOutputStream extends OutputStream and implements ObjectOutput and ObjectStreamConstants, as shown in Figure 19.15. ObjectOutput is a subinterface of DataOutput. DataOutput is shown in Figure 19.10. Video Note Object I/O M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 662 19.6 Object I/O 663 You may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/ OutputStream using the following constructors: // Create an ObjectInputStream public ObjectInputStream(InputStream in) // Create an ObjectOutputStream public ObjectOutputStream(OutputStream out) Listing 19.5 writes student names, scores, and current date to a file named object.dat.
  • 40. LISTING 19.5 TestObjectOutputStream.java 1 import java.io.*; 2 3 public class TestObjectOutputStream { 4 public static void main(String[] args) throws IOException { 5 // Create an output stream for file object.dat 6 7 8 9 // Write a string, double value, and object to the file 10 output.writeUTF("John"); 11 output.writeDouble(85.5); 12 13 14 // Close output stream 15 output.close(); 16 } 17 } An ObjectOutputStream is created to write data into file object.dat in lines 6–7. A string, a double value, and an object are written to the file in lines 10– 12. To improve performance, you may add a buffer in the stream using the following statement to replace lines 6–7: ObjectOutputStream output = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream("object.dat"))); Multiple objects or primitives can be written to the stream. The objects must be read back from the corresponding ObjectInputStream with the same types and in the same order as they were written. Java’s safe casting should be used to get the
  • 41. desired type. Listing 19.6 reads data back from object.dat. LISTING 19.6 TestObjectInputStream.java 1 import java.io.*; 2 3 public class TestObjectInputStream { 4 public static void main(String[] args) 5 throws ClassNotFoundException, IOException { 6 // Create an input stream for file object.dat 7 8 9 10 // Write a string, double value, and object to the file 11 String name = input.readUTF(); 12 double score = input.readDouble(); 13 java.util.Date date = (java.util.Date)( ); 14 System.out.println(name + " " + score + " " + date); 15 input.readObject() new ObjectInputStream(new FileInputStream("object.dat")); ObjectInputStream input = output.writeObject(new java.util.Date()); new ObjectOutputStream(new FileOutputStream("object.dat")); ObjectOutputStream output = output stream output input stream input
  • 42. M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 663 664 Chapter 19 Binary I/O 16 // Close output stream 17 input.close(); 18 } 19 } John 85.5 Mon Jun 26 17:17:29 EDT 2006 The readObject()method may throw java.lang. ClassNotFoundException. The reason is that when the JVM restores an object, it first loads the class for the object if the class has not been loaded. Since ClassNotFoundException is a checked exception, the main method declares to throw it in line 5. An ObjectInputStream is created to read input from object.dat in lines 7–8. You have to read the data from the file in the same order and format as they were written to the file. A string, a double value, and an object are read in lines 11–13. Since readObject() returns an Object, it is cast into Date and assigned to a Date variable in line 13. 19.6.1 The Serializable Interface Not every object can be written to an output stream. Objects that can be so written are said to be serializable. A serializable object is an instance of the java.io.Serializable inter- face, so the object’s class must implement Serializable.
  • 43. The Serializable interface is a marker interface. Since it has no methods, you don’t need to add additional code in your class that implements Serializable. Implementing this interface enables the Java serialization mechanism to automate the process of storing objects and arrays. To appreciate this automation feature, consider what you otherwise need to do in order to store an object. Suppose you want to store a JButton object. To do this you need to store all the current values of the properties (e.g., color, font, text, alignment) in the object. Since JButton is a subclass of AbstractButton, the property values of AbstractButton have to be stored as well as the properties of all the superclasses of AbstractButton. If a prop- erty is of an object type (e.g., background of the Color type), storing it requires storing all the property values inside this object. As you can see, this is a very tedious process. Fortu- nately, you don’t have to go through it manually. Java provides a built-in mechanism to auto- mate the process of writing objects. This process is referred to as object serialization, which is implemented in ObjectOutputStream. In contrast, the process of reading objects is referred to as object deserialization, which is implemented in ObjectInputStream. Many classes in the Java API implement Serializable. The utility classes, such as java.util.Date, and all the Swing GUI component classes implement Serializable. Attempting to store an object that does not support the Serializable interface would cause
  • 44. a NotSerializableException. When a serializable object is stored, the class of the object is encoded; this includes the class name and the signature of the class, the values of the object’s instance variables, and the closure of any other objects referenced from the initial object. The values of the object’s static variables are not stored. Note nonserializable fields If an object is an instance of Serializable but contains nonserializable instance data fields, can it be serialized? The answer is no. To enable the object to be serialized, mark these data fields with the transient keyword to tell the JVM to ignore them when writing the object to an object stream. Consider the following class: public class Foo implements java.io.Serializable { private int v1; private double v2; private A v3 = new A(); } class A { } // A is not serializable transient static ClassNotFoundException serializable
  • 45. serialization deserialization NotSerializable- Exception transient M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 664 19.6 Object I/O 665 When an object of the Foo class is serialized, only variable v1 is serialized. Variable v2 is not serialized because it is a static variable, and variable v3 is not serialized because it is marked transient. If v3 were not marked transient, a java.io.NotSerializable- Exception would occur. Note duplicate objects If an object is written to an object stream more than once, will it be stored in multiple copies? No, it will not. When an object is written for the first time, a serial number is created for it. The JVM writes the complete content of the object along with the serial number into the object stream. After the first time, only the serial number is stored if the same object is written again. When the objects are read back, their references are the same, since only one object is actually created in the
  • 46. memory. 19.6.2 Serializing Arrays An array is serializable if all its elements are serializable. An entire array can be saved using writeObject into a file and later can be restored using readObject. Listing 19.7 stores an array of five int values and an array of three strings and reads them back to display on the console. LISTING 19.7 TestObjectStreamForArray.java 1 import java.io.*; 2 3 public class TestObjectStreamForArray { 4 public static void main(String[] args) 5 throws ClassNotFoundException, IOException { 6 int[] numbers = {1, 2, 3, 4, 5}; 7 String[] strings = {"John", "Jim", "Jake"}; 8 9 // Create an output stream for file array.dat 10 11 12 13 14 // Write arrays to the object output stream 15 16 17 18 // Close the stream 19 output.close(); 20 21 // Create an input stream for file array.dat 22 23 24 25
  • 47. 26 27 28 // Display arrays 29 for (int i = 0; i < newNumbers.length; i++) 30 System.out.print(newNumbers[i] + " "); 31 System.out.println(); 32 33 for (int i = 0; i < newStrings.length; i++) 34 System.out.print(newStrings[i] + " "); 35 } 36 } String[] newStrings = (String[])(input.readObject()); int[] newNumbers = (int[])(input.readObject()); new ObjectInputStream(new FileInputStream("array.dat")); ObjectInputStream input = output.writeObject(strings); output.writeObject(numbers); ("array.dat", true)); new ObjectOutputStream(new FileOutputStream ObjectOutputStream output = output stream store array input stream restore array M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 665
  • 48. 666 Chapter 19 Binary I/O Creates a RandomAccessFile stream with the specified File object and mode. Creates a RandomAccessFile stream with the specified file name, string, and mode. Closes the stream and releases the resource associated with it. Returns the offset, in bytes, from the beginning of the file to where the next read or write occurs. Returns the length of this file. Reads a byte of data from this file and returns –1 at the end of stream. Reads up to b.length bytes of data from this file into an array of bytes. Reads up to len bytes of data from this file into an array of bytes. Sets the offset (in bytes specified in pos) from the beginning of the stream to where the next read or write occurs. Sets a new length for this file. Skips over n bytes of input. Writes b.length bytes from the specified byte array to this file,
  • 49. starting at the current file pointer. Writes len bytes from the specified byte array, starting at offset off, to this file. java.io.RandomAccessFile +RandomAccessFile(file: File, mode: String) +RandomAccessFile(name: String, mode: String) +close(): void +getFilePointer(): long +length(): long +read(): int +read(b: byte[]): int +read(b: byte[], off: int, len: int): int +seek(pos: long): void +setLength(newLength: long): void +skipBytes(int n): int +write(b: byte[]): void +write(b: byte[], off: int, len: int): void
  • 50. «interface» java.io.DataOutput «interface» java.io.DataInput FIGURE 19.16 RandomAccessFile implements the DataInput and DataOutput interfaces with additional methods to support random access. 1 2 3 4 5 John Jim Jake Lines 15–16 write two arrays into file array.dat. Lines 25–26 read three arrays back in the same order they were written. Since readObject() returns Object, casting is used to cast the objects into int[] and String[]. 19.7 Random-Access Files All of the streams you have used so far are known as read-only or write-only streams. The exter- nal files of these streams are sequential files that cannot be updated without creating a new file. It is often necessary to modify files or to insert new records into files. Java provides the RandomAccessFile class to allow a file to be read from and written to at random locations. The RandomAccessFile class implements the DataInput and DataOutput interfaces, as shown in Figure 19.16. The DataInput interface shown in Figure 19.9 defines the meth- ods (e.g., readInt, readDouble, readChar, readBoolean, readUTF) for reading primi-
  • 51. tive type values and strings, and the DataOutput interface shown in Figure 19.10 defines the methods (e.g., writeInt, writeDouble, writeChar, writeBoolean, writeUTF) for writing primitive type values and strings. read-only write-only sequential When creating a RandomAccessFile, you can specify one of two modes (“r” or “rw”). Mode “r” means that the stream is read-only, and mode “rw” indicates that the stream allows M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 666 19.7 Random-Access Files 667 both read and write. For example, the following statement creates a new stream, raf, that allows the program to read from and write to the file test.dat: RandomAccessFile raf = new RandomAccessFile("test.dat", "rw"); If test.dat already exists, raf is created to access it; if test.dat does not exist, a new file named test.dat is created, and raf is created to access the new file. The method raf.length() returns the number of bytes in test.dat at any given
  • 52. time. If you append new data into the file, raf.length() increases. Tip If the file is not intended to be modified, open it with the "r" mode. This prevents unintentional modification of the file. A random-access file consists of a sequence of bytes. A special marker called a file pointer is positioned at one of these bytes. A read or write operation takes place at the location of the file pointer. When a file is opened, the file pointer is set at the beginning of the file. When you read or write data to the file, the file pointer moves forward to the next data item. For exam- ple, if you read an int value using readInt(), the JVM reads 4 bytes from the file pointer, and now the file pointer is 4 bytes ahead of the previous location, as shown in Figure 19.17. file pointer For a RandomAccessFile raf, you can use the raf.seek(position) method to move the file pointer to a specified position. raf.seek(0) moves it to the beginning of the file, and raf.seek(raf.length()) moves it to the end of the file. Listing 19.8 demonstrates RandomAccessFile. A large case study of using RandomAccessFile to organize an address book is given in Supplement VII.B. LISTING 19.8 TestRandomAccessFile.java 1 import java.io.*; 2
  • 53. 3 public class TestRandomAccessFile { 4 public static void main(String[] args) throws IOException { 5 // Create a random-access file 6 7 8 // Clear the file to destroy the old contents, if any 9 10 11 // Write new integers to the file 12 for (int i = 0; i < 200; i++) 13 14 15 // Display the current length of the file 16 System.out.println("Current file length is " + ); 17 inout.length() inout.writeInt(i); inout.setLength(0); RandomAccessFile inout = new RandomAccessFile("inout.dat", "rw"); RandomAccessFile empty file write (b) After readInt() File pointer File File
  • 54. … byte byte byte byte byte byte byte byte byte byte… (a) Before readInt()byte byte byte byte byte byte byte bytebyte byte byte byte byte… …byte File pointer FIGURE 19.17 After an int value is read, the file pointer is moved 4 bytes ahead. M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 667 668 Chapter 19 Binary I/O 18 // Retrieve the first number 19 // Move the file pointer to the beginning 20 System.out.println("The first number is " + ); 21 22 // Retrieve the second number 23 // Move the file pointer to the second number 24 System.out.println("The second number is " + ); 25 26 // Retrieve the tenth number 27 // Move the file pointer to the tenth number 28 System.out.println("The tenth number is " + ); 29 30 // Modify the eleventh number 31 32 33 // Append a new number 34 // Move the file pointer to the end 35
  • 55. 36 37 // Display the new length 38 System.out.println("The new length is " + ); 39 40 // Retrieve the new eleventh number 41 // Move the file pointer to the next number 42 System.out.println("The eleventh number is " + ); 43 44 inout.close(); 45 } 46 } inout.readInt() inout.seek(10 * 4); inout.length() inout.writeInt(999); inout.seek(inout.length()); inout.writeInt(555); inout.readInt() inout.seek(9 * 4); inout.readInt() inout.seek(1 * 4); inout.readInt() inout.seek(0);move pointer read close file Current file length is 800
  • 56. The first number is 0 The second number is 1 The tenth number is 9 The new length is 804 The eleventh number is 555 A RandomAccessFile is created for the file named inout.dat with mode “rw” to allow both read and write operations in line 6. inout.setLength(0) sets the length to 0 in line 9. This, in effect, destroys the old con- tents of the file. The for loop writes 200 int values from 0 to 199 into the file in lines 12–13. Since each int value takes 4 bytes, the total length of the file returned from inout.length() is now 800 (line 16), as shown in sample output. Invoking inout.seek(0) in line 19 sets the file pointer to the beginning of the file. inout.readInt() reads the first value in line 20 and moves the file pointer to the next num- ber. The second number is read in line 23. inout.seek(9 * 4) (line 27) moves the file pointer to the tenth number. inout .readInt() reads the tenth number and moves the file pointer to the eleventh number in line 28. inout.write(555) writes a new eleventh number at the current position (line 31). The previous eleventh number is destroyed. inout.seek(inout.length()) moves the file pointer to the end of the file (line 34).
  • 57. inout.writeInt(999) writes a 999 to the file. Now the length of the file is increased by 4, so inout.length() returns 804 (line 38). inout.seek(10 * 4) moves the file pointer to the eleventh number in line 41. The new eleventh number, 555, is displayed in line 42. M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 668 Review Questions 669 KEY TERMS binary I/O 650 deserialization 664 file pointer 667 random-access file 667 sequential-access file 666 serialization 664 stream 650 text I/O 650 CHAPTER SUMMARY 1. I/O can be classified into text I/O and binary I/O. Text I/O interprets data in sequences of characters. Binary I/O interprets data as raw binary values. How text is stored in a file depends on the encoding scheme for the file. Java automatically performs encoding and decoding for text I/O.
  • 58. 2. The InputStream and OutputStream classes are the roots of all binary I/O classes. FileInputStream/FileOutputStream associates a file for binary input/output. BufferedInputStream/BufferedOutputStream can be used to wrap on any binary I/O stream to improve performance. DataInputStream/DataOutputStream can be used to read/write primitive values and strings. 3. ObjectInputStream/ObjectOutputStream can be used to read/write objects in addition to primitive values and strings. To enable object serialization, the object’s defining class must implement the java.io.Serializable marker interface. 4. The RandomAccessFile class enables you to read and write data to a file. You can open a file with the “r” mode to indicate that it is read-only, or with the “rw” mode to indicate that it is updateable. Since the RandomAccessFile class implements DataInput and DataOutput interfaces, many methods in RandomAccessFile are the same as those in DataInputStream and DataOutputStream. REVIEW QUESTIONS Sections 19.1–19.2 19.1 What is a text file, and what is a binary file? Can you view a text file or a binary file using a text editor? 19.2 How do you read or write data in Java? What is a stream?
  • 59. Section 19.3 19.3 What are the differences between text I/O and binary I/O? 19.4 How is a Java character represented in the memory, and how is a character repre- sented in a text file? 19.5 If you write string “ABC” to an ASCII text file, what values are stored in the file? 19.6 If you write string “100” to an ASCII text file, what values are stored in the file? If you write a numeric byte-type value 100 using binary I/O, what values are stored in the file? 19.7 What is the encoding scheme for representing a character in a Java program? By default, what is the encoding scheme for a text file on Windows? Section 19.4 19.8 Why do you have to declare to throw IOException in the method or use a try- catch block to handle IOException for Java IO programs? 19.9 Why should you always close streams? M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 669 670 Chapter 19 Binary I/O
  • 60. 19.10 InputStream reads bytes. Why does the read() method return an int instead of a byte? Find the abstract methods in InputStream and OutputStream. 19.11 Does FileInputStream/FileOutputStream introduce any new methods? How do you create a FileInputStream/FileOutputStream? 19.12 What will happen if you attempt to create an input stream on a nonexistent file? What will happen if you attempt to create an output stream on an existing file? Can you append data to an existing file? 19.13 How do you append data to an existing text file using java.io.PrintWriter? 19.14 Suppose a file contains an unspecified number of double values. Theses values were written to the file using the writeDouble method using a DataOutputStream. How do you write a program to read all these values? How do you detect the end of file? 19.15 What is written to a file using writeByte(91) on a FileOutputStream? 19.16 How do you check the end of a file in a binary input stream (FileInputStream, DataInputStream)? 19.17 What is wrong in the following code? import java.io.*;
  • 61. public class Test { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("test.dat"); } catch (IOException ex) { ex.printStackTrace(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } } } 19.18 Suppose you run the program on Windows using the default ASCII encoding. After the program is finished, how many bytes are in the file t.txt? Show the con- tents of each byte. public class Test { public static void main(String[] args) throws java.io.IOException { java.io.PrintWriter output = new java.io.PrintWriter("t.txt"); output.printf("%s", "1234"); output.printf("%s", "5678"); output.close(); }
  • 62. } 19.19 After the program is finished, how many bytes are in the file t.dat? Show the con- tents of each byte. import java.io.*; public class Test { public static void main(String[] args) throws IOException { DataOutputStream output = new DataOutputStream( M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 670 Review Questions 671 new FileOutputStream("t.dat")); output.writeInt(1234); output.writeInt(5678); output.close(); } } 19.20 For each of the following statements on a DataOutputStream out, how many bytes are sent to the output? output.writeChar('A'); output.writeChars("BC"); output.writeUTF("DEF"); 19.21 What are the advantages of using buffered streams? Are
  • 63. the following statements correct? BufferedInputStream input1 = new BufferedInputStream(new FileInputStream("t.dat")); DataInputStream input2 = new DataInputStream( new BufferedInputStream(new FileInputStream("t.dat"))); ObjectInputStream input3 = new ObjectInputStream( new BufferedInputStream(new FileInputStream("t.dat"))); Section 19.6 19.22 What types of objects can be stored using the ObjectOutputStream? What is the method for writing an object? What is the method for reading an object? What is the return type of the method that reads an object from ObjectInputStream? 19.23 If you serialize two objects of the same type, will they take the same amount of space? If not, give an example. 19.24 Is it true that any instance of java.io.Serializable can be successfully seri- alized? Are the static variables in an object serialized? How do you mark an instance variable not to be serialized? 19.25 Can you write an array to an ObjectOutputStream? 19.26 Is it true that DataInputStream/DataOutputStream can always be replaced by ObjectInputStream/ObjectOutputStream?
  • 64. 19.27 What will happen when you attempt to run the following code? import java.io.*; public class Test { public static void main(String[] args) throws IOException { ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("object.dat")); output.writeObject(new A()); } } class A implements Serializable { B b = new B(); } class B { } M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 671 672 Chapter 19 Binary I/O Section 19.7 19.28 Can RandomAccessFile streams read and write a data file created by DataOutputStream? Can RandomAccessFile streams read and
  • 65. write objects? 19.29 Create a RandomAccessFile stream for the file address.dat to allow the updat- ing of student information in the file. Create a DataOutputStream for the file address.dat. Explain the differences between these two statements. 19.30 What happens if the file test.dat does not exist when you attempt to compile and run the following code? import java.io.*; public class Test { public static void main(String[] args) { try { RandomAccessFile raf = new RandomAccessFile("test.dat", "r"); int i = raf.readInt(); } catch (IOException ex) { System.out.println("IO exception"); } } } PROGRAMMING EXERCISES Section 19.3 19.1* (Creating a text file) Write a program to create a file named Exercise19_1.txt if it
  • 66. does not exist. Append new data to it. Write 100 integers created randomly into the file using text I/O. Integers are separated by a space. Section 19.4 19.2* (Creating a binary data file) Write a program to create a file named Exercise19_2.dat if it does not exist. Append new data to it. Write 100 integers created randomly into the file using binary I/O. 19.3* (Summing all the integers in a binary data file) Suppose a binary data file named Exercise19_3.dat has been created using writeInt(int) in DataOutput- Stream. The file contains an unspecified number of integers. Write a program to find the sum of integers. 19.4* (Converting a text file into UTF) Write a program that reads lines of characters from a text and writes each line as a UTF-8 string into a binary file. Display the sizes of the text file and the binary file. Use the following command to run the program: java Exercise19_4 Welcome.java Welcome.utf Section 19.6 19.5* (Storing objects and arrays into a file) Write a program that stores an array of five int values 1, 2, 3, 4 and 5, a Date object for current time, and a double value 5.5
  • 67. into the file named Exercise19_5.dat. M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 672 Programming Exercises 673 FIGURE 19.18 The application can store, retrieve, and update addresses from a file. (a) (b) FIGURE 19.19 (a) The program splits a file. (b) The program combines files into a new file. 19.6* (Storing Loan objects) The Loan class, in Listing 10.2, does not implement Serializable. Rewrite the Loan class to implement Serializable. Write a program that creates five Loan objects and stores them in a file named Exercise19_6.dat. 19.7* (Restoring objects from a file) Suppose a file named Exercise19_7.dat has been created using the ObjectOutputStream. The file contains Loan objects. The Loan class, in Listing 10.2, does not implement Serializable. Rewrite the Loan class to implement Serializable. Write a program that reads the Loan objects from the file and computes the total loan amount. Sup- pose you don’t know how many Loan objects are in the file. Use
  • 68. EOFException to end the loop. Section 19.7 19.8* (Updating count) Suppose you want to track how many times a program has been executed. You may store an int to count the file. Increase the count by 1 each time this program is executed. Let the program be Exercise19_8 and store the count in Exercise19_8.dat. 19.9*** (Address book) Supplement VII.B gives a case study of using random-access files for creating and manipulating an address book. Modify the case study by adding an Update button, as shown in Figure 19.18, to enable the user to modify the address that is being displayed. Comprehensive 19.10* (Splitting files) Suppose you wish to back up a huge file (e.g., a 10-GB AVI file) to a CD-R. You can achieve it by splitting the file into smaller pieces and back- ing up these pieces separately. Write a utility program that splits a large file into smaller ones using the following command: java Exercise19_10 SourceFile numberOfPieces The command creates files SourceFile.1, SourceFile.2, SourceFile.n, where n is numberOfPieces and the output files are about the same size.
  • 69. 19.11** (Splitting files GUI) Rewrite Exercise 19.10 with a GUI, as shown in Figure 19.19(a). Á , Video Note Split a large file M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 673 674 Chapter 19 Binary I/O BitOutputStream +BitOutputStream(file: File) +writeBit(char bit): void +writeBit(String bit): void +close(): void Creates a BitOutputStream to write bit to the file. Write a bit '0' or '1' to the output stream. Write a string of bits to the output stream. This method must be invoked to close the stream. FIGURE 19.20 BitOutputStream outputs a stream of bits to a
  • 70. file. 19.12* (Combining files) Write a utility program that combines the files together into a new file using the following command: java Exercise19_12 SourceFile1 SoureFilen TargetFile The command combines SourceFile1, and SourceFilen into TargetFile. 19.13* (Combining files GUI) Rewrite Exercise 19.12 with a GUI, as shown in Figure 19.19(b). 19.14 (Encrypting files) Encode the file by adding 5 to every byte in the file. Write a program that prompts the user to enter an input file name and an output file name and saves the encrypted version of the input file to the output file. 19.15 (Decrypting files) Suppose a file is encrypted using the scheme in Exercise 19.14. Write a program to decode an encrypted file. Your program should prompt the user to enter an input file name and an output file name and should save the unencrypted version of the input file to the output file. 19.16 (Frequency of characters) Write a program that prompts the user to enter the name of an ASCII text file and display the frequency of the characters in the file. 19.17** (BitOutputStream) Implement a class named
  • 71. BitOutputStream, as shown in Figure 19.20, for writing bits to an output stream. The writeBit(char bit) method stores the bit in a byte variable. When you create a BitOutputStream, the byte is empty. After invoking writeBit('1'), the byte becomes 00000001. After invoking writeBit("0101"), the byte becomes 00010101. The first three bits are not filled yet. When a byte is full, it is sent to the output stream. Now the byte is reset to empty. You must close the stream by invoking the close() method. If the byte is not empty and not full, the close() method first fills the zeros to make a full 8 bits in the byte, and then output the byte and close the stream. For a hint, see Exercise 4.46. Write a test program that sends the bits 010000100100001001101 to the file named Exercise19_17.dat. Á , Á 19.18* (View bits) Write the following method that displays the bit representation for the last byte in an integer: public static String getBits(int value) For a hint, see Exercise 4.46. Write a program that prompts the user to enter a file name, reads bytes from a file, and displays each byte’s binary
  • 72. representation. 19.19* (View hex) Write a program that prompts the user to enter a file name, reads bytes from a file, and displays each byte’s hex representation. (Hint: You may first convert the byte value into an 8-bit string, then convert the bit string into a two-digit hex string.) M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 674 Programming Exercises 675 (a) (b) FIGURE 19.21 The exercises enable the user to manipulate the contents of the file in binary and hex. 19.20** (Binary Editor) Write a GUI application that lets the user enter a file name in the text field and press the Enter key to display its binary representation in a text area. The user can also modify the binary code and save it back to the file, as shown in Figure 19.21(a). 19.21** (Hex Editor) Write a GUI application that lets the user enter a file name in the text field and press the Enter key to display its hex representation in a text area. The user can also modify the hex code and save it back to the file, as shown in
  • 73. Figure 19.21(b). M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 675 M19_LIAN0807_08_SE_C19.QXD 11/10/09 4:40 PM Page 676 1 Chapter 17 Binary I/O
  • 74. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 2 Motivations Data stored in a text file is represented in human-readable form. Data stored in a binary file is represented in binary form. You cannot read binary files. They are designed to be read by programs. For example, Java source programs are stored in text files and can be read by a text editor, but Java classes are stored in binary files and are read by the JVM. The advantage of binary files is that they are more efficient to process than text files.
  • 75. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 3 Objectives To discover how I/O is processed in Java (§17.2). To distinguish between text I/O and binary I/O (§17.3). To read and write bytes using FileInputStream and FileOutputStream (§17.4.1). To read and write primitive values and strings using DataInputStream/DataOutputStream (§17.4.3). To store and restore objects using ObjectOutputStream and ObjectInputStream, and to understand how objects are serialized and what kind of objects can be serialized (§17.6). To implement the Serializable interface to make objects serializable (§17.6.1). To serialize arrays (§17.6.2). To read and write the same file using the RandomAccessFile class (§17.7).
  • 76. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 4 How is I/O Handled in Java? A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes. PrintWriter output = new PrintWriter("temp.txt"); output.println("Java 101"); output.close(); Scanner input = new Scanner(new File("temp.txt")); System.out.println(input.nextLine());
  • 77. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 5 Text File vs. Binary File Data stored in a text file are represented in human-readable
  • 78. form. Data stored in a binary file are represented in binary form. You cannot read binary files. Binary files are designed to be read by programs. For example, the Java source programs are stored in text files and can be read by a text editor, but the Java classes are stored in binary files and are read by the JVM. The advantage of binary files is that they are more efficient to process than text files. Although it is not technically precise and correct, you can imagine that a text file consists of a sequence of characters and a binary file consists of a sequence of bits. For example, the decimal integer 199 is stored as the sequence of three characters: '1', '9', '9' in a text file and the same integer is stored as a byte-type value C7 in a binary file, because decimal 199 equals to hex C7.
  • 79. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 6 Binary I/O Text I/O requires encoding and decoding. The JVM converts a Unicode to a file specific encoding when writing a character and coverts a file specific encoding to a Unicode when reading a character. Binary I/O does not require conversions. When you write a byte to a file, the original byte is copied into the file. When you read a byte from a file, the exact byte in the file is returned.
  • 80. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 7 Binary I/O Classes
  • 81. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 8 The value returned is a byte as an int type. InputStream
  • 82. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 9 The value is a byte as an int type. OutputStream
  • 83. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 10 FileInputStream/FileOutputStream FileInputStream/FileOutputStream associates a binary input/output stream with an external file. All the methods in FileInputStream/FileOuptputStream are inherited from its superclasses.
  • 84. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 11 FileInputStream To construct a FileInputStream, use the following constructors: public FileInputStream(String filename) public FileInputStream(File file) A java.io.FileNotFoundException would occur if you attempt to create a FileInputStream with a nonexistent file.
  • 85. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 12 FileOutputStream To construct a FileOutputStream, use the following constructors: public FileOutputStream(String filename) public FileOutputStream(File file) public FileOutputStream(String filename, boolean append) public FileOutputStream(File file, boolean append) If the file does not exist, a new file would be created. If the file already exists, the first two constructors would delete the current contents in the file. To retain the current content and append new data into the file, use the last two constructors by passing true to the append parameter. TestFileStream Run
  • 86. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 13 FilterInputStream/FilterOutputStream Filter streams are streams that filter bytes for some purpose. The basic byte input stream provides a read method that can only be used for reading bytes. If you want to read integers,
  • 87. doubles, or strings, you need a filter class to wrap the byte input stream. Using a filter class enables you to read integers, doubles, and strings instead of bytes and characters. FilterInputStream and FilterOutputStream are the base classes for filtering data. When you need to process primitive numeric types, use DatInputStream and DataOutputStream to filter bytes.
  • 88. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 14 DataInputStream/DataOutputStream DataInputStream reads bytes from the stream and converts them into appropriate primitive type values or strings. DataOutputStream converts primitive type values or strings into bytes and output the bytes to the stream.
  • 89. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 15 DataInputStream DataInputStream extends FilterInputStream and implements the DataInput interface.
  • 90. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 16 DataOutputStream DataOutputStream extends FilterOutputStream and implements the DataOutput interface.
  • 91. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 17 Characters and Strings in Binary I/O A Unicode consists of two bytes. The writeChar(char c) method writes the Unicode of character c to the output. The writeChars(String s) method writes the Unicode for each character in the string s to the output. Why UTF-8? What is UTF-8? UTF-8 is a coding scheme that allows systems to operate with both ASCII and Unicode efficiently. Most operating systems use ASCII. Java uses Unicode. The ASCII character set is a subset of the Unicode character set. Since most applications need only the ASCII character set, it is a waste to represent an 8-bit ASCII character as a 16-bit Unicode character. The UTF-8 is an alternative scheme that stores a character using 1, 2, or 3 bytes. ASCII values (less than 0x7F) are coded in one byte. Unicode values less than 0x7FF are coded in two bytes. Other Unicode values are coded in three bytes.
  • 92. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 18 Using DataInputStream/DataOutputStream Data streams are used as wrappers on existing input and output streams to filter data in the original stream. They are created using the following constructors: public DataInputStream(InputStream instream) public DataOutputStream(OutputStream outstream) The statements given below create data streams. The first statement creates an input stream for file in.dat; the second statement creates an output stream for file out.dat. DataInputStream infile = new DataInputStream(new FileInputStream("in.dat")); DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat")); TestDataStream Run
  • 93. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 19 Checking End of File 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. Order and Format
  • 94. 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. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 20 BufferedInputStream/ BufferedOutputStream
  • 95. Using buffers to speed up I/O BufferedInputStream/BufferedOutputStream does not contain new methods. All the methods BufferedInputStream/BufferedOutputStream are inherited from the InputStream/OutputStream classes. Liang, Introduction to Java Programming, Tenth Edition, (c)
  • 96. 2013 Pearson Education, Inc. All rights reserved. 21 Concept of pipe line Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 22
  • 97. Constructing BufferedInputStream/BufferedOutputStream // Create a BufferedInputStream public BufferedInputStream(InputStream in) public BufferedInputStream(InputStream in, int bufferSize) // Create a BufferedOutputStream public BufferedOutputStream(OutputStream out) public BufferedOutputStream(OutputStreamr out, int bufferSize)
  • 98. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 23 Case Studies: Copy File This case study develops a program that copies files. The user needs to provide a source file and a target file as command-line arguments using the following command: java Copy source target The program copies a source file to a target file and displays the number of bytes in the file. If the source does not exist, tell the user the file is not found. If the target file already exists, tell the user the file already exists. Copy Run
  • 99. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 24 Object I/O DataInputStream/DataOutputStream enables you to perform I/O for primitive type values and strings. ObjectInputStream/ObjectOutputStream enables you to perform I/O for objects in addition for primitive type values and strings. Optional
  • 100. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 25 ObjectInputStream ObjectInputStream extends InputStream and implements ObjectInput and ObjectStreamConstants.
  • 101. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 26 ObjectOutputStream ObjectOutputStream extends OutputStream and implements ObjectOutput and ObjectStreamConstants.
  • 102. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 27 Using Object Streams You may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/OutputStream using the following constructors:
  • 103. // Create an ObjectInputStream public ObjectInputStream(InputStream in) // Create an ObjectOutputStream public ObjectOutputStream(OutputStream out) TestObjectOutputStream Run TestObjectInputStream Run
  • 104. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 28 The Serializable Interface Not all objects can be written to an output stream. Objects that can be written to an object stream is said to be serializable. A serializable object is an instance of the java.io.Serializable interface. So the class of a serializable object must implement Serializable. The Serializable interface is a marker interface. It has no methods, so you don't need to add additional code in your class that implements Serializable. Implementing this interface enables the Java serialization mechanism to automate the process of storing the objects and arrays.
  • 105. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 29 The transient Keyword If an object is an instance of Serializable, but it contains non- serializable instance data fields, can the object be serialized? The answer is no. To enable the object to be serialized, you can use the transient keyword to mark these data fields to tell the JVM to ignore these fields when writing the object to an object stream.
  • 106. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 30 The transient Keyword, cont. Consider the following class: public class Foo implements java.io.Serializable { private int v1; private static double v2; private transient A v3 = new A(); } class A { } // A is not serializable When an object of the Foo class is serialized, only variable v1 is serialized. Variable v2 is not serialized because it is a static variable, and variable v3 is not serialized because it is marked transient. If v3 were not marked transient, a java.io.NotSerializableException would occur.
  • 107. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 31 Serializing Arrays An array is serializable if all its elements are serializable. So an entire array can be saved using writeObject into a file and later restored using readObject. Here is an example that stores an array of five int values and an array of three strings, and reads them back to display on the console. TestObjectStreamForArray Run
  • 108. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 32 Random Access Files All of the streams you have used so far are known as read-only or write-only streams. The external files of these streams are sequential files that cannot be updated without creating a new file. It is often necessary to modify files or to insert new records into files. Java provides the RandomAccessFile class to allow a file to be read from and write to at random locations.
  • 109. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 33 RandomAccessFile
  • 110. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 34 File Pointer A random access file consists of a sequence of bytes. There is a special marker called file pointer that is positioned at one of these bytes. A read or write operation takes place at the location of the file pointer. When a file is opened, the file pointer sets at the beginning of the file. When you read or write data to the file, the file pointer moves forward to the next data. For example, if you read an int value using readInt(), the JVM reads four bytes from the file pointer and now the file pointer is four
  • 111. bytes ahead of the previous location. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 35 RandomAccessFile Methods Many methods in RandomAccessFile are the same as those in DataInputStream and DataOutputStream. For example,
  • 112. readInt(), readLong(), writeDouble(), readLine(), writeInt(), and writeLong() can be used in data input stream or data output stream as well as in RandomAccessFile streams. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 36 RandomAccessFile Methods, cont. void seek(long pos) throws IOException; Sets the offset from the beginning of the
  • 113. RandomAccessFile stream to where the next read or write occurs. long getFilePointer() IOException; Returns the current offset, in bytes, from the beginning of the file to where the next read or write occurs. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 37
  • 114. RandomAccessFile Methods, cont. long length()IOException Returns the length of the file. final void writeChar(int v) throws IOException Writes a character to the file as a two-byte Unicode, with the high byte written first. final void writeChars(String s) throws IOException Writes a string to the file as a sequence of characters.
  • 115. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 38 RandomAccessFile Constructor RandomAccessFile raf = new RandomAccessFile("test.dat", "rw"); // allows read and write RandomAccessFile raf = new RandomAccessFile("test.dat", "r"); // read only
  • 116. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 39 A Short Example on RandomAccessFile Run TestRandomAccessFile
  • 117. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 40 Case Studies: Address Book Now let us use RandomAccessFile to create a useful project for storing and viewing and address book. The Add button stores a new address to the end of the file. The First, Next, Previous, and Last buttons retrieve the first, next, previous, and last addresses from the file, respectively. Companion Website
  • 118. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 41 Fixed Length String I/O Random access files are often used to process files of records. For convenience, fixed-length records are used in random access files so that a record can be located easily. A record consists of a fixed number of fields. A field can be a string or a primitive data type. A string in a fixed-length record has a maximum size. If a string is smaller than the maximum size, the rest of the string is padded with blanks. FixedLengthStringIO Companion Website
  • 119. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 42 Address Implementation The rest of the work can be summarized in the following steps: Create the user interface. Add a record to the file. Read a record from the file. Write the code to implement the button actions. Run AddressBook Companion Website
  • 120. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. Program Input object created from an input class Output object created from an output class Input stream Output stream
  • 121. File File 01011…1001 11001…1011 Program Input object created from an input class File Output object created from an output class 01011…1001 File
  • 122. Input stream Output stream 11001…1011 java.io.InputStream +read(): int +read(b: byte[]): int +read(b: byte[], off: int, len: int): int +available(): int +close(): void +skip(n: long): long +markSupported(): boolean
  • 123. +mark(readlimit: int): void +reset(): void Reads the next byte of d ata from the input stream. The value byte is returned as an int value in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value – 1 is returned. Reads up to b.length bytes into array b from the input stream and returns the actual number of bytes read. Returns - 1 at the end of the stream. Reads bytes from the input stream and stores into b[off], b[off+1], …, b[off+len - 1]. The actual number of bytes read is returned. Returns - 1 at the end of the stream. Returns the number of bytes that can be read from the input stream. Closes this input stream and releases any system resources associated with the stream.
  • 124. Skips over and discards n bytes of data from this input stream. The actual number of bytes skipped is returne d. Tests if this input stream supports the mark and reset methods. Marks the current position in this input stream. Repositions this stream to the position at the time the mark method was last called on this input stream. java.io.InputStream +read(): int +read(b: byte[]): int +read(b: byte[], off: int, len: int): int +available(): int +close(): void
  • 125. +skip(n: long): long +markSupported(): boolean +mark(readlimit: int): void +reset(): void Reads the next byte of data from the input stream. The value byte is returned as an int value in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value –1 is returned. Reads up to b.length bytes into array b from the input stream and returns the actual number of bytes read. Returns -1 at the end of the stream. Reads bytes from the input stream and stores into b[off], b[off+1], …, b[off+len-1]. The actual number of bytes read is returned. Returns -1 at the end of the stream. Returns the number of bytes that can be read from the input stream.
  • 126. Closes this input stream and releases any system resources associated with the stream. Skips over and discards n bytes of data from this input stream. The actual number of bytes skipped is returned. Tests if this input stream supports the mark and reset methods. Marks the current position in this input stream. Repositions this stream to the position at the time the mark method was last called on this input stream. java.io.OutputStream +write(int b): void +write(b: byte[]): void +write(b: byte[], off: int, len: int): void
  • 127. +close(): void +flush(): void Writes the specified byte to this output stream. The parameter b is an int value. (byte)b is written to th e output stream. Writes all the bytes in array b to the output stream. Writes b[off], b[off+1], …, b[off+len - 1] into the output stream. Closes this output stream and releases any system resources associated with the stream. Flushes this output stream and forces any buffered output bytes to be written out. java.io.OutputStream +write(int b): void +write(b: byte[]): void
  • 128. +write(b: byte[], off: int, len: int): void +close(): void +flush(): void Writes the specified byte to this output stream. The parameter b is an int value. (byte)b is written to the output stream. Writes all the bytes in array b to the output stream. Writes b[off], b[off+1], …, b[off+len-1] into the output stream. Closes this output stream and releases any system resources associated with the stream. Flushes this output stream and forces any buffered output bytes to be written out.
  • 140. OutputStream InputStream DataInputStream FileInputStream External File 01000110011 … int, double, string … DataOutputStream FileOutputStream External File 01000110011 … int, double, string …
  • 141. FileInputStream int, double, string … 01000110011 … External File FileOutputStream DataInputStream DataOutputStream int, double, string …
  • 145. OutputStream InputStream java.io.ObjectInput +readObject(): Object Reads an object. java.io.InputStream java.io.ObjectInputStream +ObjectInputStream(in: InputStream) java.io.DataInput ObjectStreamConstants
  • 146. java.io.InputStream java.io.ObjectInput +readObject(): Object Reads an object. java.io.DataInput java.io.ObjectInputStream +ObjectInputStream(in: InputStream) ObjectStreamConstants
  • 147. java.io.ObjectOutput +writeObject(o: Object): void Writes an object. java.io.OutputStream java.io.ObjectOutputStream +ObjectOutputStream(out: OutputStream) java.io.DataOutput ObjectStreamConstants java.io.OutputStream java.io.ObjectOutput +writeObject(o: Object): void
  • 149. Record n Field1 Field 2 … Field k file e.g., Student 1 Student 2 Student n name street city state zip Record n Record 2
  • 150. Field1 Field 2 … Field k Record 1 file e.g., name street city state zip Student n Student 2