21
© 2000 McGraw-Hill Introduction to Object-Oriented Programming wi th Java--Wu Chapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

Embed Size (px)

Citation preview

Page 1: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 1

Chapter 11

File Input and Output

Page 2: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 2

Chapter 11 Objectives

After you have read and studied this chapter, you should be able to

Include a FileDialog 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. Write objects to a file and read them back from the file using ObjectOutputStream and ObjectInputStream.Write exception-handling routines using the try–catch block.

Page 3: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 3

File Objects

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”,

“one.txt”);

File inFile = new File(“C:/SamplePrograms/test.dat”);

Opens the file sample.dat in the current directory.

Opens the file sample.dat in the current directory.

Opens the file one.txt in the directory C:\SamplePrograms. Notice the use of the escape character \.

Opens the file one.txt in the directory C:\SamplePrograms. Notice the use of the escape character \.

Opens the file test.dat in the directory C:\SamplePrograms using the generic file separator / and providing the full pathname.

Opens the file test.dat in the directory C:\SamplePrograms using the generic file separator / and providing the full pathname.

Page 4: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 4

Some File Methods

if ( inFile.exists( ) ) { … }

if ( inFile.isFile( ) ) { … }

File folder = new File(“C:/JavaProjects/Ch11”);

String filename[ ] = folder.list( );

for (int i=0; i < filename.length; i++ ){outputBox.printLine( filename[i] );

}

To see if inFile is associated to a real file correctly.

To see if inFile is associated to a real file correctly.

To see if inFile is associated to a file or a directory.

To see if inFile is associated to a file or a directory.

List the name of all files in the directory C:\JavaProjects\Ch11.

List the name of all files in the directory C:\JavaProjects\Ch11.

Page 5: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 5

FileDialog - Open

FileDialog is a standard file dialog for selecting a file.

FileDialog fileBox = new FileDialog( mainWindow, “Open”, FileDialog.LOAD );

fileBox.setVisible( true );

String filename = fileBox.getFile( );

Page 6: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 6

FileDialog - Save

FileDialog fileBox = new FileDialog( mainWindow, “Save As”, FileDialog.SAVE );

fileBox.setVisible( true );

Page 7: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 7

Low-Level File I/O – 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 stream (very important here)outStream.close();

Page 8: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 8

Low-Level File I/O – 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++) {

outputBox.printLine(byteArray[i]);}

//input done, so close the streaminStream.close();

Page 9: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 9

High-Level File I/O – Output

File outFile = new File("sample2.data");FileOutputStream outFileStream = new FileOutputStream(outFile);DataOutputStream outDataStream = new DataOutputStream(outFileStream);

Primitive data type values are written to outDataStream.

Primitive data type values are written to outDataStream.

Primitive data type values are converted to bytes.

Primitive data type values are converted to bytes.

Converted bytes are written to the file.

Converted bytes are written to the file.

outDataStream

writeFloatwriteInt

writeDouble

1

outFileStream

2

outFile

3

Page 10: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 10

High-Level File I/O – Input

File inFile = new File("sample2.data");FileInputStream inFileStream = new FileInputStream(inFile);DataInputStream inDataStream = new DataInputStream(inFileStream);

Primitive data type values are read from inDataStream.

Primitive data type values are read from inDataStream.

Bytes are converted to primitive data type values.

Bytes are converted to primitive data type values.

Bytes are read from the file.

Bytes are read from the file.

readFloatreadInt

readDouble

3inDataStream

2

inFileStream

outFile

1

Page 11: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 11

Textfile I/O – Output

//set up file and streamFile outFile = new File("sample3.data");FileOutputStream outFileStream = new FileOutputStream(outFile);PrintWriter outStream = new PrintWriter(outFileStream);

//write values of primitive data types to the streamoutStream.println(987654321);outStream.println(11111111L);//…outStream.println('A');outStream.println(true);

//output done, so close the streamoutStream.close();

Page 12: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 12

Textfile I/O – Input

//set up file and streamFile inFile = new File("sample3.data");FileReader fileReader = new FileReader(inFile);BufferedReader bufReader = new BufferedReader(fileReader);String str;

//get integerstr = bufReader.readLine();int i = Convert.toInt(str);

//read other data in a similar manner

//input done, so close the streambufReader.close();

Page 13: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 13

Handling Exceptions

An exception occurs when any of the semantic constraints of the Java language is violated.

An exception is said to be thrown and caught .

When our program calls a statement that can throw an exception, we must write a code to either

propagate the thrown exception or handle it by the try-block statement.

Page 14: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 14

Propagation Approach

Add the phrase throws <Exception> to the declaration for a method that includes a call to a statement that can throw exceptions. Replace <Exception> with the actual exception class, such as IOException, EOFException, and so forth.

void computeSum (String fileName ) throws IOException{ File inFile = new File(fileName);

FileInputStream inFileStream = new FileInputStream(inFile);DataInputStream inDataStream = new DataInputStream(inFileStream);

//read three integersint i = inDataStream.readInt();int j = inDataStream.readInt();int k = inDataStream.readInt();

sum = i + j + k;

inDataStream.close();}

Page 15: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 15

try-catch Approach

Use the try-catch statement to include the exception-handling routines.

void computeSum (String fileName ) {

success = true;

try {File inFile = new File(fileName);FileInputStream inFileStream = new FileInputStream(inFile);DataInputStream inDataStream = new DataInputStream(inFileStream);

//read three integersint i = inDataStream.readInt();int j = inDataStream.readInt();int k = inDataStream.readInt();

sum = i + j + k;

inDataStream.close();}catch (IOException e) {

success = false;}

}

Page 16: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 16

Handling Multiple Exceptions

You can have more than one catch clause for each try.

try {...

}catch (FileNotFoundException e) {

success = false;System.out.println("File " + fileName + " does not exist.");

}catch (EOFException e) {

success = false;System.out.println("Error: " +

"Cannot read beyond end of file");}catch (IOException e) {

success = false;System.out.println("General I/O exception is thrown");

}

Page 17: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 17

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

{

. . .

}

Page 18: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 18

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

Could save objects from the different classes.

Could save objects from the different classes.

Page 19: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 19

Loading 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 read in the correct order.

Must type cast to the correct object type.

Must type cast to the correct object type.

Page 20: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 20

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 arrayoutObjectStream.writeObject ( people );

//load the array

Person[ ] people = (Person[ ]) inObjectStream.readObject ( );

Page 21: © 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 11 - 21

Let's try one…

Start a program that asks if you want to create or open a file

If create: write three different variables to an ASCII file using an InputBox

Else Open

Save the file

When opening the file:Open the file using a dialogPrint out the file in an OutputBox