Overview
At its lowest level, all Java I/O involves a stream of bytes either entering or leaving memory as shown by this diagram:
Memory
Output stream of bytes
External device
----->
<-----
Input stream of bytes
Obviously, sending and receiving individual bytes would be tedious and difficult for an application to manage. For that reason, several packaged classes exist that make it easy for a program to read and write larger units of data.
Most programs use a "high-level" stream class object that is "chained" (connected) to a "low-level" stream class object. While the low-level stream class object handles byte I/O, the high-level stream class object will allow the program to read and write primitive data values and even objects (as shown below).
Application
"High-level" stream class object
"Low-level" stream class object
External device
<--->
<--->
primitives and objects
bytes
There are many stream classes, but you will only be required to know the ones that are highlighted below:
Direction
Low-level classes
High-level classes
Output
ByteArrayOutputStream
FileOutputStream
BufferedOutputStream
DataOutputStream
ObjectOutputStream
PrintStream
Input
ByteArrayInputStream
FileInputStream
BufferedInputStream
DataInputStream
LineNumberInputStream
ObjectInputStream
PushbackInputStream
The FileOutputStream class
Is part of the java.io package
Is an extension of the OutputStream class, an abstract class that describes the behavior of an output stream
Object
\
OutputStream \
FileOutputStream
Is a low-level class that can be used to send individual, 8-bit bytes to a stream
will construct a FileOutputStream object for sending bytes to the file. If the file already exists, its contents will be replaced (there is an overloaded constructor to specify appending). Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch.FileOutputStream out = new FileOutputStream(fd);
Method
Usage
close()
Closes the stream and releases stream resources
write()
Writes the right-most 8 bits of a specified integer value to the stream
Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details.
Example. The following program can be used to create a file of numbers on disk.
import java.io.*;
public class App {
public static void main(String[] args) {
// Local variables and object references.
char again = 'y';
File fd;
FileOutputStream out;
// Get the path name from the user.
System.out.print("Enter the file's complete path name: ");
fd = new File(Keyboard.readString());
// Try to write data to the output stream.
try {
// Open an output stream for the file.
out = new FileOutputStream(fd);
// This loop asks the user to enter a number and writes it to the
// stream. The user is then asked if they want to enter another.
while (again == 'Y' || again == 'y') {
System.out.print("Enter a number: ");
int theNumber = Keyboard.readInt();
out.write(theNumber);
System.out.print("Again? (Y/N): ");
again = Keyboard.readChar();
}
// Close the stream.
out.close();
System.out.println("Closed - " + fd.getPath());
}
// Catch an IOException if one is thrown.
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
The FileInputStream class
Is part of the java.io package
Is an extension of the InputStream class, an abstract class that describes the behavior of an input stream
Object
\
InputStream \
FileInputStream
Is a low-level class that can be used to read individual, 8-bit bytes from a stream
will construct a FileInputStream object for reading bytes from the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch.FileInputStream in = new FileInputStream(fd);
Method
Usage
available()
Returns the number of bytes that can be read from this input stream
close()
Closes the stream and releases stream resources
read()
Reads the next byte value from the input stream
Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details.
Example. The following program can be used to read byte values from a disk file. It can be used to display the values stored by the previous sample program.
import java.io.*;
public class App {
public static void main(String[] args) {
// Local variables and object references.
File fd;
FileInputStream in;
// Get the path name from the user.
System.out.print("Enter the file's complete path name: ");
fd = new File(Keyboard.readString());
// Try to read data from the input stream.
try {
// Open an input stream for the file.
in = new FileInputStream(fd);
// This loop reads a byte from the stream and displays
// its value. The loop ends when no more bytes are available.
while (in.available() > 0) {
System.out.println(in.read());
}
// Close the stream.
in.close();
System.out.println("Closed - " + fd.getPath());
}
// Catch an IOException if one is thrown.
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
The DataOutputStream class
Is part of the java.io package
Is an extension of the FilterOutputStream class (a superclass that facilitates the chaining of high-level and low-level output streams)
Object
\
OutputStream
\
FilterOutputStream
\
DataOutputStream
Is a high-level class that can be used to send primitive values and UTF ("Unicode Transformation Format") strings to a stream
will construct a DataOutputStream object chained to a FileOutputStream object for sending primitive values and UTF strings to the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch.DataOutputStream out = new DataOutputStream(new FileOutputStream(fd));
Method
Usage
writeBoolean()
Writes a specified boolean value to the stream
writeByte()
Writes a specified byte value to the stream
writeChar()
Writes a specified char value to the stream
writeDouble()
Writes a specified double value to the stream
writeFloat()
Writes a specified float value to the stream
writeInt()
Writes a specified int value to the stream
writeLong()
Writes a specified long value to the stream
writeShort()
Writes a specified short value to the stream
writeUTF()
Writes a specified String to the stream according to the UTF standard
Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details.
Example. The following program can be used to create a file of double values on disk.
import java.io.*;
public class App {
public static void main(String[] args) {
// Local variables and object references.
char again = 'y';
File fd;
DataOutputStream out;
// Get the path name from the user.
System.out.print("Enter the file's complete path name: ");
fd = new File(Keyboard.readString());
// Try to write data to the output stream.
try {
// Open an output stream for the file.
out = new DataOutputStream(new FileOutputStream(fd));
// This loop asks the user to enter a number and writes it to the
// stream. The user is then asked if they want to enter another.
while (again == 'Y' || again == 'y') {
System.out.print("Enter any real number (n.n): ");
double theNumber = Keyboard.readDouble();
out.writeDouble(theNumber);
System.out.print("Again? (Y/N): ");
again = Keyboard.readChar();
}
// Close the stream.
out.close();
System.out.println("Closed - " + fd.getPath());
}
// Catch an IOException if one is thrown.
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
The DataInputStream class
Is part of the java.io package
Is an extension of the FilterInputStream class (a superclass that facilitates the chaining of high-level and low-level input streams)
Object
\
InputStream
\
FilterInputStream
\
DataInputStream
Is a high-level class that can be used to read primitive values and UTF ("Unicode Transformation Format") strings from a stream
will construct a DataInputStream object chained to a FileInputStream object for reading primitive values and UTF strings from the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch.DataInputStream in = new DataInputStream(new FileInputStream(fd));
Method
Usage
readBoolean()
Reads a boolean value from the stream
readByte()
Reads a byte value from the stream
readChar()
Reads a char value from the stream
readDouble()
Reads a double value from the stream
readFloat()
Reads a float value from the stream
readInt()
Reads a int value from the stream
readLong()
Reads a long value from the stream
readShort()
Reads a short value from the stream
readUTF()
Reads a String from the stream according to the UTF standard
Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details.
Example. The following program can be used to read a file of double values from disk. It can be used to display the values stored by the previous sample program.
import java.io.*;
public class App {
public static void main(String[] args) {
// Local variables and object references.
File fd;
DataInputStream in;
// Get the path name from the user.
System.out.print("Enter the file's complete path name: ");
fd = new File(Keyboard.readString());
// Try to read data from the input stream.
try {
// Open an input stream for the file.
in = new DataInputStream(new FileInputStream(fd));
// This loop reads a double value from the stream and displays
// it. The loop ends when end of file is reached.
try {
while (true) {
System.out.println(in.readDouble());
}
}
catch (EOFException e) {
System.out.println("<END OF FILE>");
}
// Close the stream.
in.close();
System.out.println("Closed - " + fd.getPath());
}
// Catch an IOException if one is thrown.
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
The ObjectOutputStream class
Is part of the java.io package
Is an extension of the OutputStream class, an abstract class that describes the behavior of an output stream
Object
\
OutputStream
\
ObjectOutputStream
Is a high-level class that can be used to send primitive values and "serializable" objects to a stream. All that is needed for an object to be serializable, is that its class must implement the Serializable interface. For example, if a Customer class is to be serializable, its header may be coded
public class Customer implements Serializable
The interface requires no methods.
Many packaged classes are serializable including all wrapper classes, String and Stringbuffer classes, Vector and Array classes, and the collection classes. In other words, an entire collection, such as a SortedMap, can be stored as an object on disk!
will construct a ObjectOutputStream object chained to a FileOutputStream object for sending primitive values and serializable objects to the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch.ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fd));
Method
Usage
writeBoolean()
Writes a specified boolean value to the stream
writeByte()
Writes a specified byte value to the stream
writeChar()
Writes a specified char value to the stream
writeDouble()
Writes a specified double value to the stream
writeFloat()
Writes a specified float value to the stream
writeInt()
Writes a specified int value to the stream
writeLong()
Writes a specified long value to the stream
writeObject()
Writes a specified serializable object to the stream
writeShort()
Writes a specified short value to the stream
writeUTF()
Writes a specified String to the stream according to the UTF standard
Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details.
Example. The following program can be used to create a file of multiple array objects on disk.
import java.io.*;
public class App {
public static void main(String[] args) {
// Local variables and object references.
char again = 'y';
String[] array;
File fd;
ObjectOutputStream out;
// Get the path name from the user.
System.out.print("Enter the file's complete path name: ");
fd = new File(Keyboard.readString());
// Try to write data to the output stream.
try {
// Open an output stream for the file.
out = new ObjectOutputStream(new FileOutputStream(fd));
// This loop constructs an array with values entered by the user
// and writes the array to the file. The user is given the option
// of repeating the loop to construct and store another array.
while (again == 'Y' || again == 'y') {
System.out.print("How many strings will you enter? ");
array = new String[Keyboard.readInt()];
for (int i = 0; i < array.length; i++) {
System.out.print("Enter a string: ");
array[i] = Keyboard.readString();
}
out.writeObject(array);
System.out.print("Again? (Y/N) ");
again = Keyboard.readChar();
}
// Close the stream.
out.close();
System.out.println("Closed - " + fd.getPath());
}
// Catch an IOException if one is thrown.
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
The ObjectInputStream class
Is part of the java.io package
Is an extension of the InputStream class, an abstract class that describes the behavior of an input stream
Object
\
InputStream
\
ObjectInputStream
Is a high-level class that can be used to read primitive values and serializable objects from a stream
will construct a ObjectInputStream object chained to a FileInputStream object for reading primitive values and serializable objects from the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch.ObjectInputStream out = new ObjectInputStream(new FileInputStream(fd));
Method
Usage
readBoolean()
Reads a boolean value from the stream
readByte()
Reads a byte value from the stream
readChar()
Reads a char value from the stream
readDouble()
Reads a double value from the stream
readFloat()
Reads a float value from the stream
readInt()
Reads a int value from the stream
readLong()
Reads a long value from the stream
readObject()
Reads an object from the stream
readShort()
Reads a short value from the stream
readUTF()
Reads a String from the stream according to the UTF standard
Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details.
Example. The following program can be used to read a file of array objects from disk. It can be used to display the array values stored by the previous sample program.
import java.io.*;
public class App {
public static void main(String[] args) {
// Local variables and object references.
File fd;
ObjectInputStream in;
// Get the path name from the user.
System.out.print("Enter the file's complete path name: ");
fd = new File(Keyboard.readString());
// Try to read data from the input stream.
try {
// Open an input stream for the file.
in = new ObjectInputStream(new FileInputStream(fd));
// This loop reads a array objects from the stream and displays
// their contents. The loop ends when end of file is reached.
try {
while (true) {
String[] array = (String[]) in.readObject();
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
System.out.println("<< END OF ARRAY >>");
}
}
catch (EOFException e) {
System.out.println("<< END OF FILE >>");
}
// Close the stream.
in.close();
System.out.println("Closed - " + fd.getPath());
}
// Catch an IOException if one is thrown.
catch (IOException e) {
System.out.println(e.getMessage());
}
// Catch an ClassNotFoundException if one is thrown.
catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
Looking ahead
All the files in this lesson were sequential. The data was stored in a particular order and read in the same order. In the next lesson you will learn how to create and use a random access file in which an item of data may be read from or written to an existing file based upon its position within the file.
Review questions
Which of the following provide a method for reading of an int value from a stream? (choose two)
ObjectInputStream
FileInputStream
FileStream
InputStream
DataInputStream
What will happen when an attempt is made to compile and execute the following program? The line numbers are for reference purposes only.
1
2
3
4
5
6
7
8
9import java.io.*;
public class App {
public static void main(String[] args) {
File fd = new File("c:\\temp\\myfile.dat");
FileOutputStream out = new FileOutputStream(fd);
out.write(123);
out.close();
}
}
The program will not compile
The code will compile but a runtime exception will occur
The program will compile and execute to store the int value 123 in the disk file
The program will compile and execute to store the byte value 123 in the disk file
The program will compile and execute but nothing will be stored in the disk file
If fd is a File object containing a path name, code a single statement to construct a DataInputStream object named istream for the file.
True or False: If the following is the header of an instantiable class, an object of the class can be written to disk using a DataOutputStream.
public class someClass implements Serializable
True
False