1 / 21

Chapter 11

Chapter 11. File Input and Output. 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.

spetrie
Download Presentation

Chapter 11

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 11 File Input and Output Introduction to Object-Oriented Programming with Java--Wu

  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. Introduction to Object-Oriented Programming with Java--Wu

  3. File inFile = new File(“sample.dat”); File inFile = new File (“C:/SamplePrograms/test.dat”); File inFile = new File(“C:\\SamplePrograms”, “one.txt”); File Objects • To operate on a file, we must first create a File object (from java.io). 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. Introduction to Object-Oriented Programming with Java--Wu

  4. 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] ); } Some File Methods 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. Introduction to Object-Oriented Programming with Java--Wu

  5. FileDialog fileBox = new FileDialog( mainWindow, “Open”, FileDialog.LOAD ); fileBox.setVisible( true ); String filename = fileBox.getFile( ); FileDialog - Open • FileDialog is a standard file dialog for selecting a file. Introduction to Object-Oriented Programming with Java--Wu

  6. FileDialog fileBox = new FileDialog( mainWindow, “Save As”, FileDialog.SAVE ); fileBox.setVisible( true ); FileDialog - Save Introduction to Object-Oriented Programming with Java--Wu

  7. //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(); Low-Level File I/O – Output Introduction to Object-Oriented Programming with Java--Wu

  8. //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(); Low-Level File I/O – Input Introduction to Object-Oriented Programming with Java--Wu

  9. File outFile = new File("sample2.data"); FileOutputStream outFileStream = new FileOutputStream(outFile); DataOutputStream outDataStream = new DataOutputStream(outFileStream); writeInt writeFloat writeDouble 1 outDataStream 2 outFileStream 3 outFile High-Level File I/O – Output Primitive data type values are written to outDataStream. Primitive data type values are converted to bytes. Converted bytes are written to the file. Introduction to Object-Oriented Programming with Java--Wu

  10. File inFile = new File("sample2.data"); FileInputStream inFileStream = new FileInputStream(inFile); DataInputStream inDataStream = new DataInputStream(inFileStream); readInt readFloat readDouble 3 inDataStream 2 inFileStream 1 outFile High-Level File I/O – Input Primitive data type values are read from inDataStream. Bytes are converted to primitive data type values. Bytes are read from the file. Introduction to Object-Oriented Programming with Java--Wu

  11. //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(); Textfile I/O – Output Introduction to Object-Oriented Programming with Java--Wu

  12. //set up file and stream File inFile = new File("sample3.data"); FileReader fileReader = new FileReader(inFile); BufferedReader bufReader = 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(); Textfile I/O – Input Introduction to Object-Oriented Programming with Java--Wu

  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. Introduction to Object-Oriented Programming with Java--Wu

  14. 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(); • } 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. Introduction to Object-Oriented Programming with Java--Wu

  15. 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; } } try-catch Approach • Use the try-catch statement to include the exception-handling routines. Introduction to Object-Oriented Programming with Java--Wu

  16. 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"); } Handling Multiple Exceptions • You can have more than one catch clause for each try. Introduction to Object-Oriented Programming with Java--Wu

  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 { . . . } Introduction to Object-Oriented Programming with Java--Wu

  18. Person person = new Person("Mr. Espresso", 20, 'M'); outObjectStream.writeObject( person ); File outFile = new File("objects.data"); FileOutputStream outFileStream = new FileOutputStream(outFile); ObjectOutputStream outObjectStream = new ObjectOutputStream(outFileStream); account1 = new Account(); bank1 = new Bank(); outObjectStream.writeObject( account1 ); outObjectStream.writeObject( bank1 ); Saving Objects Could save objects from the different classes. Introduction to Object-Oriented Programming with Java--Wu

  19. 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( ); Loading Objects Must type cast to the correct object type. Must read in the correct order. Introduction to Object-Oriented Programming with Java--Wu

  20. 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 ( ); Saving and Loading Arrays • Instead of processing array elements individually, it is possible to save and load the whole array at once. Introduction to Object-Oriented Programming with Java--Wu

  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 Introduction to Object-Oriented Programming with Java--Wu

More Related