Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output."— Presentation transcript:

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

2 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 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.

3 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 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 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.

4 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 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 file or a directory. List the name of all files in the directory C:\JavaProjects\Ch11.

5 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 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( );

6 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 11 - 6 FileDialog - Save FileDialog fileBox = new FileDialog( mainWindow, “Save As”, FileDialog.SAVE ); fileBox.setVisible( true );

7 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 11 - 7 Low-Level File I/O – 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 (very important here) outStream.close();

8 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 11 - 8 Low-Level File I/O – 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++) { outputBox.printLine(byteArray[i]); } //input done, so close the stream inStream.close();

9 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 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 converted to bytes. Converted bytes are written to the file. outDataStream writeFloat writeInt writeDouble 1 outFileStream 2 outFile 3

10 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 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. Bytes are converted to primitive data type values. Bytes are read from the file. readFloat readInt readDouble 3 inDataStream 2 inFileStream outFile 1

11 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 11 - 11 Textfile I/O – Output //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(11111111L); //… outStream.println('A'); outStream.println(true); //output done, so close the stream outStream.close();

12 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 11 - 12 Textfile I/O – Input //set up file and stream FileinFile = new File("sample3.data"); FileReaderfileReader = new FileReader(inFile); BufferedReaderbufReader = new BufferedReader(fileReader); String str; //get integer str = bufReader.readLine(); int i = Convert.toInt(str); //read other data in a similar manner //input done, so close the stream bufReader.close();

13 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 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.

14 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 11 - 14 Propagation Approach Add the phrase throws to the declaration for a method that includes a call to a statement that can throw exceptions. Replace 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 integers int i = inDataStream.readInt(); int j = inDataStream.readInt(); int k = inDataStream.readInt(); sum = i + j + k; inDataStream.close(); }

15 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 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 integers int i = inDataStream.readInt(); int j = inDataStream.readInt(); int k = inDataStream.readInt(); sum = i + j + k; inDataStream.close(); } catch (IOException e) { success = false; }

16 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 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"); }

17 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 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 {... }

18 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 11 - 18 Saving Objects FileoutFile = 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.

19 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 11 - 19 Loading Objects FileinFile = 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.

20 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 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 array outObjectStream.writeObject ( people ); //load the array Person[ ] people = (Person[ ]) inObjectStream.readObject ( );

21 © 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 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 dialog Print out the file in an OutputBox


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

Similar presentations


Ads by Google