Presentation is loading. Please wait.

Presentation is loading. Please wait.

File Input and Output Recitation 04/03/2009 CS 180 Department of Computer Science, Purdue University.

Similar presentations


Presentation on theme: "File Input and Output Recitation 04/03/2009 CS 180 Department of Computer Science, Purdue University."— Presentation transcript:

1 File Input and Output Recitation 04/03/2009 CS 180 Department of Computer Science, Purdue University

2 Announcements Project 7 is out  Fun project! With animation!  Start early…… Exam grade has been released ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 2

3 3 Pass-by Value/Reference public class A { private int x = 0, y = 0; public A(int a) { this(a, 5); } public A(int a, int b) {x = a; y = b; } public A(A a) { this(a.getX(), a.getY()); } public int getX() { return x; } public int getY() { return y; } public void setX(int a) { x = a; } public void setY(int a) { y = a; } public static void swap(A a1, A a2) { A atemp = a1; a1 = a2; a2 = atemp; } public static void swap(AContainer aa1, AContainer aa2) { A atemp = aa1.a; aa1.a = aa2.a; aa2.a = atemp; } public class AContainer { public A a; public AContainer(A a) {this.a = a;} } A a1 = new A(0); A a2 = new A(a1); a1.setX(10); a1.setY(15); A.swap(a1, a2); a1.getX() == 10 a1.getY() == 15 a2.getX() == 0 a2.getY() == 5 A a1 = new A(0); A a2 = new A(a1); a1.setX(10); a1.setY(15); A.swap(a1, a2); a1.getX() == 10 a1.getY() == 15 a2.getX() == 0 a2.getY() == 5

4 4 File I/O What is it for?  Store your data.  Your photos, music, documents, etc.  So your data is not lost after closing the program.  If you saved your data, you can get back what you saved after your program crashes. How to use it?  Files are represented as objects in Java File inFile = new File(“sample.dat”); Class type Variable name Create a new object

5 Example You would like to save my Minesweeper game and continue later.  Saving the current minefield (digits)  Saving the state (covered, uncovered, flagged)  Saving the game state (in progress, win, lose)  … ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 5

6 What can you do with File? Is it exist? .exists() Is it a file or folder? .isFile() Get all files in a folder .list() Delete .delete() Rename .renameTo() And many others… ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 6

7 Selecting files with JFileChooser ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 7 // Create a new JFileChooser // JFileChooser is just another class in Java JFileChooser chooser = new JFileChooser( ); // Show the Dialog box int status = chooser.showOpenDialog(null); // Do nothing and return if the user clicked Cancel if (status != JFileChooser.APPROVE_OPTION) return; // At this point, the user selected a file, get the selected file. File selectedFile = chooser.getSelectedFile(); // Print out the name of the file selected. JOptionPane.showMessageDialog(null, “You selected a file named “ + selectedFile.getName()); // Open the file for processing (reading/writing) etc………… This is how you prompt the user for the filename to save/open a file. E.g. where to save your Minesweeper game This is how you prompt the user for the filename to save/open a file. E.g. where to save your Minesweeper game

8 Reading/Writing to Files Definitions  Stream: A sequence of bytes  Input stream: Stream to read data from  Output stream: Stream to write data to Streams for file  FileOutputStream : Write a sequence of bytes to a file.  FileInputStream : Read a sequence of bytes from a file. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 8

9 Example Writing to File ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 9 // Continue from slide 7 File selectedFile = chooser.getSelectedFile(); // Or hardcode the filename: File selectedFile = new File(“savedGame.dat”); // Create a FileOutputStream object, and it writes to selectedFile. FileOutputStream outStream = new FileOutputStream( selectedFile ); // Pack all the data to save into an array of byte. // For example, declare an array and copy the digit array in Minesweeper game into // a byte array. byte[] data = {10, 20, 30, 40, 50, 60, 70, 80}; // Write data to the output stream, which will save it to the file. outStream.write( data ); // Close the stream when everything is done. outStream.close();

10 Example Reading from File ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 10 // Continue from slide 7 File selectedFile = chooser.getSelectedFile(); // Or hardcode the filename: File selectedFile = new File(“savedGame.dat”); // Create a FileInputStream object, and it reads from selectedFile. FileInputStream inStream = new FileInputStream(selectedFile); // Create an array large enough to hold the data int fileSize = (int)selectedFile.length();// Get the length of the file. byte[] byteArray = new byte[fileSize];// Create an array of that size // Read all data from the file. inStream.read(byteArray); // Print out the data read or do other processing // For example, put back the data read into the digit array of your // minesweeper game. for (int i = 0; i < fileSize; i++) System.out.println(byteArray[i]); // input done, so close the stream inStream.close();

11 Remember to Close your File When you’re done with the file. Close it! Closing the file, make sure everything is written to disk. // Close the stream when everything is done. outStream.close(); // input done, so close the stream inStream.close(); What if you did not?  Corrupted file: The file may not be written properly.  You cannot open the same file again until you close it. We must close a file after writing before we can read from it in the same program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 11

12 Must I convert it to byte[]? No. If you use FileOutputStream, then you can only read/write byte[].  Need to convert data from other types to byte[] Any simpler way? Yes  Use DataOutputStream above FileOutputStream You can write byte, char, int, string, double, float, …  To read the data back correctly, we must know the order of the data stored and their data types 12

13 Saving your Minefield to file ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 13 // Continue from slide 7 File selectedFile = chooser.getSelectedFile(); // Or hardcode the filename: File selectedFile = new File(“savedGame.dat”); // Create a FileOutputStream object, and it writes to selectedFile. FileOutputStream outStream = new FileOutputStream( selectedFile ); DataOutputStream dataStream = new DataOutputStream( outStream ); // Save the mine field to the file using dataStream. // dataStream will convert the integer to bytes[] and write // it to outStream outStream will write the data to the // underlying file. for(int i = 0; i < 10; i++) for(int j = 0; j < 10; j++) dataStream.writeInt(digit[i][j]); // Close the stream when everything is done. dataStream.close();

14 Reading your Minefield from file ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 14 // Continue from slide 7 File selectedFile = chooser.getSelectedFile(); // Or hardcode the filename: File selectedFile = new File(“savedGame.dat”); // Create a FileInputStream object, and it reads from selectedFile. FileInputStream inStream = new FileInputStream( selectedFile ); DataInputStream dataStream = new DataInputStream( inStream ); // Read the mine field from the file using dataStream. for(int i = 0; i < 10; i++) for(int j = 0; j < 10; j++) digit[i][j] = dataStream.readInt(); // Close the stream when everything is done. dataStream.close(); Make sure you read in the same order as you write

15 Text Files What if you want to write everything in text?  DataOutputStream writes data in binary Not readible to human  Use PrintWriter (Writing)  Use FileReader, BufferedReader (Reading) ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 15

16 Saving your Minefield to text file ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 16 // Continue from slide 7 File selectedFile = chooser.getSelectedFile(); // Or hardcode the filename: File selectedFile = new File(“savedGame.dat”); // Create a FileOutputStream object, and it writes to selectedFile. FileOutputStream outStream = new FileOutputStream( selectedFile ); PrintWriter dataStream = new PrintWriter( outStream ); // Save the mine field to the file using dataStream. // dataStream will convert the integer to bytes[] and write // it to outStream outStream will write the data to the // underlying file. for(int i = 0; i < 10; i++) for(int j = 0; j < 10; j++) dataStream.println(digit[i][j]); // Close the stream when everything is done. dataStream.close();

17 Reading Minefield from text file ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 17 // Continue from slide 7 File selectedFile = chooser.getSelectedFile(); // Or hardcode the filename: File selectedFile = new File(“savedGame.dat”); // Create a FileInputStream object, and it reads from selectedFile. FileReader fileReader = new FileReader( selectedFile ); BufferedReader bufReader = new BufferedReader( fileReader ); // Read the text from file and parse it to integer. String s; for(int i = 0; i < 10; i++) for(int j = 0; j < 10; j++) { s = bufReader.readLine(); digit[i][j] = Integer.parseInt(s); } // Close the reader when everything is done. bufReader.close();

18 Writing to Existing File If a file with the given name exists it is opened for output and its current content are lost. If we want to retain the old data, and append to the end of the file. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 18

19 Scanner Why we need to put System.in when we create a Scanner object?  That tells the scanner where to read from.  System.in meaning reads from the keyboard. To read from a file, we can do Scanner scanner = new Scanner(new File(“savedGame.data")); scanner.close(); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 19 You need to close the scanner!

20 Saving the Whole Object Is there any easy way to save the whole GameMaster class, other than saving individual variables?  Yes! Use ObjectOutputStream and ObjectInputStream  But the class must implements Serializable  Public class GameMaster implements Serializable { … } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 20

21 Saving/Loading GameMaster ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 21 // Continue from slide 7 File selectedFile = chooser.getSelectedFile(); // Or hardcode the filename: File selectedFile = new File(“savedGame.dat”); // Create a FileOutputStream object, and it writes to selectedFile. FileOutputStream outStream = new FileOutputStream( selectedFile ); ObjectOutputStream objStream = new ObjectOutputStream( outStream ); // Write the whole GameMaster class to the file objStream.writeObject(gameMaster); objStream.close(); // Create a FileOutputStream object, and it writes to selectedFile. FileInputStream inStream = new FileInputStream( selectedFile ); ObjectInputStream objStream = new ObjectInputStream( inStream ); // Write the whole GameMaster class to the file GameMaster gameMaster = (GameMaster)objStream.readObject(); objStream.close(); Save to file Read from file

22 Exceptions? Use extensively when you do File IO  FileNotFoundException  IOException If you remove your USB drive while writing to it. Reading past the end of file Reading/writing being interrupted File is not in the correct format  Need to handle them well to make your application robust ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 22

23 Example with Exception ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 23 // Copied from slide 17 try { FileReader fileReader = new FileReader( selectedFile ); BufferedReader bufReader = new BufferedReader( fileReader ); String s; for(int i = 0; i < 10; i++) for(int j = 0; j < 10; j++) { s = bufReader.readLine(); digit[i][j] = Integer.parseInt(s); }} finally { // Close the reader when everything is done. bufReader.close();}

24 Quiz What happen if you do not read in the same order as you write? ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 24


Download ppt "File Input and Output Recitation 04/03/2009 CS 180 Department of Computer Science, Purdue University."

Similar presentations


Ads by Google