Chapter 12
File Input and Output
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 1
Chapter 12 Objectives
• After you have read and studied this chapter, you should
be able to
– Include a JFileChooser object in your program to let the user
specify a file.
– Write bytes to a file and read them back from the file, using
FileOutputStream and FileInputStream.
– Write values of primitive data types to a file and read them back
from the file, using DataOutputStream and DataInputStream.
– Write text data to a file and read them back from the file, using
PrintWriter and BufferedReader
– Read a text file using Scanner
– Write objects to a file and read them back from the file, using
ObjectOutputStream and ObjectInputStream
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 2
The File Class
• To operate on a file, we must first create a File object (from
java.io).
Opens
Opensthethefile
filesample.dat
sample.dat
File inFile = new File(“sample.dat”); ininthe current directory.
the current directory.
Opens
Opensthe thefile
filetest.dat
test.datinin
File inFile = new File the
thedirectory
directory
(“C:/SamplePrograms/test.dat”); C:\SamplePrograms
C:\SamplePrograms
using
usingthe
thegeneric
genericfilefile
separator / and
separator / and
providing
providingthethefull
full
pathname.
pathname.
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 3
Some File Methods
To
Tosee
seeififinFile
inFileisis
if ( inFile.exists( ) ) { associated
associatedtotoaarealrealfile
file
correctly.
correctly.
if ( inFile.isFile() ) { To
Tosee
seeififinFile
inFileisis
associated
associatedtotoaafile fileor
or
not. If false, it is a
not. If false, it is a
directory.
directory.
File directory = new List
Listthe
thename
nameofofall
allfiles
files
File("C:/JavaPrograms/Ch12"); ininthe directory
the directory
C:\JavaProjects\Ch12
C:\JavaProjects\Ch12
String filename[] = directory.list();
for (int i = 0; i < filename.length; i++) {
System.out.println(filename[i]);
}
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 4
The JFileChooser Class
• A javax.swing.JFileChooser object allows the
user to select a file.
JFileChooser chooser = new JFileChooser( );
chooser.showOpenDialog(null);
To start the listing from a specific directory:
JFileChooser chooser = new JFileChooser("D:/JavaPrograms/Ch12");
chooser.showOpenDialog(null);
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 5
Getting Info from JFileChooser
int status = chooser.showOpenDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null, "Open is clicked");
} else { //== JFileChooser.CANCEL_OPTION
JOptionPane.showMessageDialog(null, "Cancel is clicked");
}
File selectedFile = chooser.getSelectedFile();
File currentDirectory = chooser.getCurrentDirectory();
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 6
Applying a File Filter
• A file filter may be used to restrict the listing in
JFileChooser to only those files/directories that
meet the designated filtering criteria.
• To apply a file, we define a subclass of the
javax.swing.filechooser.FileFilter class and
provide the accept and getDescription methods.
public boolean accept(File file)
public String getDescription( )
• See the JavaFilter class that restricts the listing to
directories and Java source files.
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 7
12.2 Low-Level File I/O
• To read data from or write data to a file, we must
create one of the Java stream objects and attach it
to the file.
• A stream is a sequence of data items, usually 8-bit
bytes.
• Java has two types of streams: an input stream
and an output stream.
• An input stream has a source form which the data
items come, and an output stream has a
destination to which the data items are going.
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 8
Streams for Low-Level File I/O
• FileOutputStream and FileInputStream are two
stream objects that facilitate file access.
• FileOutputStream allows us to output a sequence
of bytes; values of data type byte.
• FileInputStream allows us to read in an array of
bytes.
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 9
Sample: Low-Level File Output
//set up file and stream
File outFile = new File("sample1.data");
FileOutputStream
outStream = new FileOutputStream( outFile );
//data to save
byte[] byteArray = {10, 20, 30, 40,
50, 60, 70, 80};
//write data to the stream
outStream.write( byteArray );
//output done, so close the stream
outStream.close();
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 10
Sample: Low-Level File Input
//set up file and stream
File inFile = new File("sample1.data");
FileInputStream inStream = new FileInputStream(inFile);
//set up an array to read data in
int fileSize = (int)inFile.length();
byte[] byteArray = new byte[fileSize];
//read data in and display them
inStream.read(byteArray);
for (int i = 0; i < fileSize; i++) {
System.out.println(byteArray[i]);
}
//input done, so close the stream
inStream.close();
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 11
Streams for High-Level File I/O
• FileOutputStream and DataOutputStream are
used to output primitive data values
• FileInputStream and DataInputStream are used to
input primitive data values
• To read the data back correctly, we must know the
order of the data stored and their data types
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 12
Setting up DataOutputStream
• A standard sequence to set up a DataOutputStream object:
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 13
Sample Output
import java.io.*;
class Ch12TestDataOutputStream {
public static void main (String[] args) throws IOException {
. . . //set up outDataStream
//write values of primitive data types to the stream
outDataStream.writeInt(987654321);
outDataStream.writeLong(11111111L);
outDataStream.writeFloat(22222222F);
outDataStream.writeDouble(3333333D);
outDataStream.writeChar('A');
outDataStream.writeBoolean(true);
//output done, so close the stream
outDataStream.close();
}
}
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 14
Setting up DataInputStream
• A standard sequence to set up a DataInputStream object:
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 15
Sample Input
import java.io.*;
class Ch12TestDataInputStream {
public static void main (String[] args) throws IOException {
. . . //set up inDataStream
//read values back from the stream and display them
System.out.println(inDataStream.readInt());
System.out.println(inDataStream.readLong());
System.out.println(inDataStream.readFloat());
System.out.println(inDataStream.readDouble());
System.out.println(inDataStream.readChar());
System.out.println(inDataStream.readBoolean());
//input done, so close the stream
inDataStream.close();
}
}
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 16
Reading Data Back in Right Order
• The order of write and read operations must match in order
to read the stored primitive data back correctly.
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 17
Textfile Input and Output
• Instead of storing primitive data values as binary
data in a file, we can convert and store them as a
string data.
– This allows us to view the file content using any text
editor
• To output data as a string to file, we use a
PrintWriter object
• To input data from a textfile, we use FileReader
and BufferedReader classes
– From Java 5.0 (SDK 1.5), we can also use the Scanner
class for inputting textfiles
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 18
Sample Textfile Output
import java.io.*;
class Ch12TestPrintWriter {
public static void main (String[] args) throws IOException {
//set up file and stream
File outFile = new File("sample3.data");
FileOutputStream outFileStream
= new FileOutputStream(outFile);
PrintWriter outStream = new PrintWriter(outFileStream);
//write values of primitive data types to the stream
outStream.println(987654321);
outStream.println("Hello, world.");
outStream.println(true);
//output done, so close the stream
outStream.close();
}
}
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 19
Sample Textfile Input
import java.io.*;
class Ch12TestBufferedReader {
public static void main (String[] args) throws IOException {
//set up file and stream
File inFile = new File("sample3.data");
FileReader fileReader = new FileReader(inFile);
BufferedReader bufReader = new BufferedReader(fileReader);
String str;
str = bufReader.readLine();
int i = Integer.parseInt(str);
//similar process for other data types
bufReader.close();
}
}
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 20
Sample Textfile Input with Scanner
import java.io.*;
class Ch12TestScanner {
public static void main (String[] args) throws IOException {
//open the Scanner
Scanner scanner = new Scanner(new File("sample3.data"));
//get integer
int i = scanner.nextInt();
//similar process for other data types
scanner.close();
}
}
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 21
Object File I/O
• It is possible to store objects just as easily as you store
primitive data values.
• We use ObjectOutputStream and ObjectInputStream to
save to and load objects from a file.
• To save objects from a given class, the class declaration
must include the phrase implements Serializable. For
example,
class Person implements Serializable {
. . .
}
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 22
Saving Objects
File outFile
= new File("objects.data");
FileOutputStream outFileStream
= new FileOutputStream(outFile);
ObjectOutputStream outObjectStream
= new ObjectOutputStream(outFileStream);
Person person = new Person("Mr. Espresso", 20, 'M');
outObjectStream.writeObject( person );
account1 = new Account();
bank1 = new Bank(); Could
Couldsave
saveobjects
objects
from the different
from the different
outObjectStream.writeObject( account1 ); classes.
classes.
outObjectStream.writeObject( bank1 );
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 23
Reading Objects
File inFile
= new File("objects.data");
FileInputStream inFileStream
= new FileInputStream(inFile);
ObjectInputStream inObjectStream
= new ObjectInputStream(inFileStream);
Person person Must
Musttype
typecast
cast
totothe correct
the correct
= (Person) inObjectStream.readObject( );
object
objecttype.
type.
Account account1
= (Account) inObjectStream.readObject( ); Must
Mustread
readininthe
the
Bank bank1 correct order.
correct order.
= (Bank) inObjectStream.readObject( );
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 24
Saving and Loading Arrays
• Instead of processing array elements individually, it is
possible to save and load the whole array at once.
Person[] people = new Person[ N ];
//assume N already has a value
//build the people array
. . .
//save the array
outObjectStream.writeObject ( people );
//read the array
Person[ ] people = (Person[]) inObjectStream.readObject( );
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 25
Problem Statement
• Problem statement:
Write a class that manages file I/O of an
AddressBook object.
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 26
Development Steps
• We will develop this program in four steps:
1. Implement the constructor and the setFile
method.
2. Implement the write method.
3. Implement the read method.
4. Finalize the class.
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 27
Step 1 Design
• We identify the data members and define a
constructor to initialize them.
• Instead of storing individual Person objects, we
will deal with a AddressBook object directly using
Object I/O techniques.
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 28
Step 1 Code
Program source file is too big to list here. From now on, we ask
you to view the source files using your Java IDE.
Directory:
Directory: Chapter12/Step1
Chapter12/Step1
Source
Source Files:
Files: AddressBookStorage.java
AddressBookStorage.java
TestAddressBookStorage.java
TestAddressBookStorage.java
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 29
Step 1 Test
• We include a temporary output statement inside
the setFile method.
• We run the test main class and verify that the
setFile method is called correctly.
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 30
Step 2 Design
• Design and implement the write method
• The data member filename stores the name
of the object file to store the address book.
• We create an ObjectOutputStream object
from the data member filename in the write
method.
• The write method will propagate an
IOException when one is thrown.
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 31
Step 2 Code
Directory:
Directory: Chapter12/Step2
Chapter12/Step2
Source
Source Files:
Files: AddressBookStorage.java
AddressBookStorage.java
TestAddressBookWrite.java
TestAddressBookWrite.java
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 32
Step 2 Test
• We run the test program several times with different sizes
for the address book.
• We verify that the resulting files indeed have different
sizes.
• At this point, we cannot check whether the data are saved
correctly or not.
– We can do so only after finishing the code to read the data back.
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 33
Step 3 Design
• Design and implement the read method.
• The method returns an AddressBook object read
from a file (if there's no exception)
• The method will propagate an IOException when
one is thrown.
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 34
Step 3 Code
Directory:
Directory: Chapter12/Step3
Chapter12/Step3
Source
Source Files:
Files: AddressBookStorage.java
AddressBookStorage.java
TestAddressBookRead.java
TestAddressBookRead.java
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 35
Step 3 Test
• We will write a test program to verify that the data can be
read back correctly from a file.
• To test the read operation, the file to read the data from
must already exist.
• We will make this test program save the data first by using
the TestAddressBookWrite class from .
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 36
Step 4: Finalize
• We perform the critical review of the final
program.
• We run the final test
©The McGraw-Hill Companies, Inc. Permission re
quired for reproduction or display. 4th Ed Chapter N - 37