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

Slides:



Advertisements
Similar presentations
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 12 File Input and Output Animated Version.
Advertisements

Chapter 19 Binary I/O.
Lecture 15: I/O and Parsing
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Files CSC 171 FALL 2001 LECTURE 18. History Operating Systems Operating systems (originally called monitors or supervisors) had been developed in the.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12 File Input and Output.
File input and output. Interactive vs. file I/O All of the programs we have seen or written thus far have assumed interaction with a user, who types in.
© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter Chapter 11 File Input and Output.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 12 File Input and Output.
 We can use a combination of the File and FileOutputStream to write a series of bytes to a file.
Simple Java I/O Part I General Principles. 2 Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
Chapter 91 Streams and File I/O Chapter 9. 2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12 File Input and Output.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L07 (Chapter 18) Binary I/O.
File I/O in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 18 Binary I/O.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 12 File Input and Output.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Chapter 91 Streams and File I/O Chapter 9. 2 Reminders Project 6 released: due Nov 10:30 pm Project 4 regrades due by midnight tonight Discussion.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: IO *Standard Output *Formatting Decimal.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Files and Streams 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
CIS 270—Application Development II Chapter 14—Files and Streams.
Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) –it acts as.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
Working with files By the end of this lecture you should be able to: explain the principles of input and output and identify a number of different input.
Chapter 17 Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams  Use JFileChooser F Text Input.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Files and Streams. Midterm exam Time: Wednesday, October 31, 2007 Format: Multiple choices (about 15 to 20 questions) Determine the results of the code.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Program data (instance variables, local variables, and parameters) is transient, because its lifetime ends with the program...if not, before. Sometimes.
Working with files. RHS – SOC 2 Motivation All our programs so far have only worked with data stored in primary storage (RAM) Data is lost when program.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
JAVA I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
Winter 2006CISC121 - Prof. McLeod1 Last Time Misc. useful classes in Java: –String –StringTokenizer –Math –System.
Selection sort and Merge sort File input/output. HW 2 – Section 02 Avg = 96/100.
By Rachel Thompson and Michael Deck.  Java.io- a package for input and output  File I/O  Reads data into and out of the console  Writes and reads.
Two Ways to Store Data in a File  Text format  Binary format.
CIS 270—App Dev II Big Java Chapter 19 Files and Streams.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
Streams and File I/O Chapter 9. Outline Overview of Streams and File I/O Text-File I/O Using the File Class Basic Binary-File I/O Object I/O with Object.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
 Pearson Education, Inc. All rights reserved Files and Streams.
1 Chapter 19 Binary I/O. 2 Motivations F Data stored in a text file – is represented in human-readable form –Text file –Readable –Java source programs.
 Learn about computer files  Use the Path class  Learn about  Streams  Buffers  file organization  Use Java’s IO classes to write to and read from.
Files and console applications Chapter 17 This chapter explains: What a file is How to read and write to files How to manipulate folder paths and file.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
File Input & Output1 Streams & File I/O. Introduction (1) The Java platform includes a number of packages that are concerned with the movement of data.
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
Recitation File I/O. File I/O File inFile = new File("data.txt"); File inFile = new File (“/Users/sunil/test.txt");
Introduction to OOP with Java 4th Ed, C. Thomas Wu
Introduction to programming in java
CS1101: Programming Methodology
I/O Basics.
Chapter 17 Binary I/O 1.
Accessing Files in Java
Working with files.
Chapter 17 Binary I/O Dr. Clincy - Lecture.
Chapter 12 File Input and Output
David Davenport Spring 2005
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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!

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

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

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

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

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