file input and outputcs180/spring2009web/lecture_notes/ch… · 3 file i/o remember that a computer...
TRANSCRIPT
Chapter 12
File Input and Output
CS 180Sunil PrabhakarDepartment of Computer Science Purdue University
2
Persistent Data
Suppose we write a Bank application. How do we remember the account
balances? What if the bank application stops running?
Runtime exception Power failure? …
How do we ensure that when we restart the application, the balances are set correctly?
3
File I/O
Remember that a computer system has two types of memory Fast, volatile main memory Slower, non-volatile secondary memory (disk)
When a program runs, its variables (primitive and objects) are stored in main memory.
When the program terminates, all these variables are lost!
If we would like to preserve values of variables across multiple executions we must save them on disk and read them back in -- file input and output File I/O.
4
File I/O
Files can also be used to prevent loss of data due to system failures.
Files can serve as a means for sharing data between different programs.
Different operating systems manage files differently.
Since Java is a HLL, we are mostly shielded from these differences.
In Java we use objects to perform file I/O.
5
Chapter 12 Objectives
This week we will study Choosing files using JFileChooser Reading from and writing to files
Bytes using FileOutputStream and FileInputStream. Primitive data types using DataOutputStream and
DataInputStream. Text data using PrintWriter and BufferedReader Objects using ObjectOutputStream and
ObjectInputStream Reading a text file using Scanner
6
The File Class To operate on a file, we must first create a File
object (from java.io).
File inFile = new File(“sample.dat”);
File inFile = new File (“C:/SamplePrograms/test.dat”);
Opens the file sample.dat in the current directory.
Opens the file test.dat in the directory C:\SamplePrograms using the generic file separator / and providing the full pathname.
7
File names
The rules for file names are determined by the operating system on which the Java program is run.
Thus the name may or may not be case sensitive, or require filename extensions…
Java simply passes the string to the operating system.
8
Some File Methodsif ( inFile.exists( ) ) {
if ( inFile.isFile() ) {
File directory = new File("C:/JavaPrograms/Ch12");
String filename[] = directory.list();
for (int i = 0; i < filename.length; i++) { System.out.println(filename[i]);}
To see if inFile is associated to a real file correctly.
To see if inFile is associated to a file or not. If false, it is a directory.
List the name of all files in the directory C:\JavaProjects\Ch12
9
The JFileChooser Class
A javax.swing.JFileChooser object allows the user to select a file.
JFileChooser chooser = new JFileChooser( );
chooser.showOpenDialog(null);
JFileChooser chooser = new JFileChooser("D:/JavaPrograms/Ch12");
chooser.showOpenDialog(null);
To start the listing from a specific directory:
10
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();
11
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 filter, 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.
12
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.
13
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.
14
Sample: Low-Level File Output
//set up file and streamFile outFile = new File("sample1.data");
FileOutputStream outStream = new FileOutputStream( outFile );
//data to savebyte[] byteArray = {10, 20, 30, 40, 50, 60, 70, 80};
//write data to the streamoutStream.write( byteArray );
//output done, so close the streamoutStream.close();
15
Sample: Low-Level File Input
//set up file and streamFile inFile = new File("sample1.data");FileInputStream inStream = new FileInputStream(inFile);
//set up an array to read data inint fileSize = (int)inFile.length();byte[] byteArray = new byte[fileSize];
//read data in and display theminStream.read(byteArray);for (int i = 0; i < fileSize; i++) { System.out.println(byteArray[i]);}
//input done, so close the streaminStream.close();
16
Opening and closing files
When we create the stream object we open the file and connect it to the stream for input or output.
Once we are done, we must close the stream. Otherwise, we may see corrupt data in the file.
If a program does not close a file and terminates normally, the system closes the files for it.
We must close a file after writing before we can read from it in the same program.
17
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
18
Setting up DataOutputStream
File outFile = new File( "sample2.data" );
FileOutputStream outFileStream = new FileOutputStream(outFile);
DataOutputStream outDataStream = new DataOutputSteam(outFileStream);
outFilesample2.dat
writeFloat writeInt writeDouble
outFileStream
Primitive data typevalues are written toourDataStream.
Primitive data typevalues are converted toa sequence of bytes.
Bytes are written to thefile one at a time.
outDataStream
19
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(); }}
20
Setting up DataInputStream
File inFile = new File( "sample2.data" );
FileInputStream inFileStream = new FileInputStream(inFile);
DataInputStream inDataStream = new DataInputSteam(inFileStream);
inFilesample2.dat
readFloat readInt readDouble
inFileStream
Primitive data typevalues are read from inDataStream.
A sequence of bytes isconverted to the primitivedata type value.
Bytes are read from thefile.
inDataStream
21
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(); }}
22
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.
outStream.writeInteger(…);outStream.writeLong(…);outStream.writeChar(…);outStream.writeBoolean(…);
inStream.readInteger(…);inStream.readLong(…);inStream.readChar(…);inStream.readBoolean(…);
<integer><long><char><boolean>
23
Types of files
There are two main types of files Text -- store characters (ASCII or UNICODE)
*.java Usually platform independent, but less efficient.
Binary -- may store any type of data. *.class, *.exe Often depend on machine (OS, program) Java binary files are platform independent.
Text files are editable using editors and usually comprehensible to humans.
So far, we have been dealing with binary files in this discussion.
24
Textfile Input and Output
Instead of storing primitive data values as binary data in a file, we can convert and store them as 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
25
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(); }}
26
PrintWriter
If a file with the given name exists it is opened for output and its current contents are lost.
If we want to retain the old data, and append to the end of the file:
FileOutputStream outFileStream = new FileOutputStream(outFile, true);
then create the PrintWriter object with this stream object.
27
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(); }}
Notes
FileReader is meant to be used for reading in character streams
FileInputStream is for arbitrary streams BufferedReader is much more efficient that
reading directly from an input stream automatically buffers input from the stream can be much more efficient due to disk I/O
costs
28
29
Sample Textfile Input with Scanner
import java.io.*;import java.util.*;
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(); }}
30
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 { . . .}
31
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();
outObjectStream.writeObject( account1 );outObjectStream.writeObject( bank1 );
Can save objects from the different classes.
32
Reading Objects
File inFile = new File("objects.data");FileInputStream inFileStream = new FileInputStream(inFile);ObjectInputStream inObjectStream = new ObjectInputStream(inFileStream);
Person person = (Person) inObjectStream.readObject( );
Account account1 = (Account) inObjectStream.readObject( );
Bank bank1 = (Bank) inObjectStream.readObject( );
Must read in the correct order.
Must type cast to the correct object type.
33
Saving and Loading Arrays Instead of processing array elements
individually, it is possible to save and load the entire array at once.
Person[] people = new Person[ N ]; //assume N already has a value
//build the people array. . .//save the arrayoutObjectStream.writeObject ( people );
//read the array
Person[ ] people = (Person[]) inObjectStream.readObject( );
34
Exceptions
File I/O methods throw various types of exceptions including IOException FileNotFoundException
Please see Java API to become familiar with these.
Many of these need to be handled in order to make programs more robust.
Labs and projects will cover some
35
Knowing when to stop reading
It is possible to try to read beyond the end of the file.
Different reader classes signal the end of file in different ways.
Binary file readers throw the EOFException.
Text file readers return null or -1. You should be aware of how the common
classes indicate the end of file condition.
36
Introducing Theory of Computation
What are the limits of computers? What can a computer not compute
Today? In 10 years? Ever?
These are some of the questions that the theory of computation tries to answer.
Covered in CS483, CS182, CS380.
37
A model for any computer
In order to answer such questions, we first begin with a model for a computer.
Actually, we begin by considering very simple machines called automata.
These are really primitive beasts, and come in several species: 1-way finite automata 2-way finite automata Turing Machine
38
The Turing Machine
Named after Alan Turing Consists of:
Input tape with symbols A control consisting of a graph Machine can:
read the current symbol, write to the current place, move the tape left or right, and change its state.
Looks primitive but is capable of computing anything that any modern computer can.
39
What are the limits of this machine?
Can it compute the factorization of a prime number?
Sure, but how long will it take? 500 digits (life of universe with a supercomputer) Security (cryptography) relies on this!!!
How long is too long? Polynomial time
Can it compute the factorization using a better algorithm in polynomial time?
Can we prove that there can be no fast algorithm for certain problems?
40
Guessing computers
Consider a Turing Machine which can take one of many options at each step.
If any guess gives us the correct answer, then we have solved the problem.
Many problems (like factoring) can be solved by such a machine in polynomial time.
But such machines do not exist.
41
NP-Completeness
Problems that can be solved in polynomial time by a “guessing” machine, but not by a Turing Machine are called NP-Complete.
If any of these is solved efficiently, then all of them will be solved efficiently!
Is this possible? I.e. is P = NP? We don’t know -- if you have the answer
you can Get the ACM Turing Award (CS Nobel Prize) Get a great job!
42
CS438, CS380, CS182
These courses study the issues of computability.
What are the limits of computers? When should we stop trying to find a fast
algorithm? If there is no (known) fast algorithm, what
can we do? Heuristics.
What happens if we get new types of computers?
43
Problem Statement
Write a class that manages file I/O of an AddressBook object.
44
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.
45
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.
46
Step 1 Code
Directory: Chapter12/Step1
Source Files: AddressBookStorage.java TestAddressBookStorage.java
Program source file is too big to list here. From now on, we askyou to view the source files using your Java IDE.
47
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.
48
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.
49
Step 2 Code
Directory: Chapter12/Step2
Source Files: AddressBookStorage.java TestAddressBookWrite.java
50
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.
51
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.
52
Step 3 Code
Directory: Chapter12/Step3
Source Files: AddressBookStorage.java TestAddressBookRead.java
53
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 .
54
Step 4: Finalize
We perform the critical review of the final program.
We run the final test