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

Slides:



Advertisements
Similar presentations
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. 2 Operating System Application #1 Application #2 Java Virtual Machine #1 Local Memory Shared Memory Threads.
Advertisements

CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
1 Streams and Input/Output Files Part 3. 2 Handling Primitive Data Types The basic input and output streams provide read/write methods that can be used.
Copyright © 2003 Pearson Education, Inc. Slide 1 Computer Systems Organization & Architecture Chapters 8-12 John D. Carpinelli.
Introduction to OOP with Java 4th Ed, C. Thomas Wu
McGraw-Hill©The McGraw-Hill Companies, Inc., 2003 Chapter 3 Data Transmission.
Introduction to OOP with Java 4th Ed, C. Thomas Wu
Chapter 1 The Study of Body Function Image PowerPoint
Copyright © 2011, Elsevier Inc. All rights reserved. Chapter 6 Author: Julia Richards and R. Scott Hawley.
Author: Julia Richards and R. Scott Hawley
UNITED NATIONS Shipment Details Report – January 2006.
REVIEW: Arthropod ID. 1. Name the subphylum. 2. Name the subphylum. 3. Name the order.
Chapter 1 Object Oriented Programming 1. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Copyright © 2012, Elsevier Inc. All rights Reserved. 1 Chapter 7 Modeling Structure with Blocks.
Chapter 19 Binary I/O.
Basel-ICU-Journal Challenge18/20/ Basel-ICU-Journal Challenge8/20/2014.
1..
CONTROL VISION Set-up. Step 1 Step 2 Step 3 Step 5 Step 4.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Analyzing Genes and Genomes
©Brooks/Cole, 2001 Chapter 12 Derived Types-- Enumerated, Structure and Union.
Intracellular Compartments and Transport
PSSA Preparation.
Essential Cell Biology
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.
Chapter 10 Ch 1 – Introduction to Computers and Java Streams and File IO 1.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
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.
©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.
King Saud University College of Computer and Information Sciences Department of Computer Science Dr. S. HAMMAMI Chapter 3 File Input/Output Chapter 3 File.
© 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.
File Input and Output Recitation 04/03/2009 CS 180 Department of Computer Science, Purdue University.
 We can use a combination of the File and FileOutputStream to write a series of bytes to a file.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
©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.
©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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Input / Output Chapter 13.  We use files all the time  Programs are files  Documents are files  We want them to be “permanent”  To last beyond execution.
Object Input/Output. Object I/O  To write objects to a file, we use ObjectOutputStream  To read objects from a file we use ObjectInputStream  Lets.
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.
Files and Streams. Midterm exam Time: Wednesday, October 31, 2007 Format: Multiple choices (about 15 to 20 questions) Determine the results of the code.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
Selection sort and Merge sort File input/output. HW 2 – Section 02 Avg = 96/100.
Two Ways to Store Data in a File  Text format  Binary format.
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.
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.
Chapter 15: Input and Output
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
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.
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
Chapter 17 Binary I/O.
Object Writing in files
CS1101: Programming Methodology
I/O Basics.
Chapter 17 Binary I/O 1.
Chapter 12 File Input and Output
Presentation transcript:

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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 12 Objectives After you have read and studied this chapter, you should be able to –Include a JFileChooser 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 –Read a text file using Scanner –Write objects to a file and read them back from the file, using ObjectOutputStream and ObjectInputStream

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter The File Class 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/test.dat); Opens the file sample.dat in the current directory. Opens the file test.dat in the directory C:\SamplePrograms using the generic file separator / and providing the full pathname.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Some File Methods if ( inFile.exists( ) ) { if ( inFile.isFile() ) { File directory = new File("C:/JavaPrograms/Ch12"); String filename[] = directory.list(); for (int i = 0; i < filename.length; i++) { System.out.println(filename[i]); } To see if inFile is associated to a real file correctly. To see if inFile is associated to a file or not. If false, it is a directory. List the name of all files in the directory C:\JavaProjects\Ch12

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter The JFileChooser Class A javax.swing.JFileChooser object allows the user to select a file. JFileChooser chooser = new JFileChooser( ); chooser.showOpenDialog(null); JFileChooser chooser = new JFileChooser(C:/JavaPrograms/Ch12"); chooser.showOpenDialog(null); To start the listing from a specific directory:

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Getting Info from JFileChooser int status = chooser.showOpenDialog(null); if (status == JFileChooser.APPROVE_OPTION) { System.out.println("Open is clicked"); } else { //== JFileChooser.CANCEL_OPTION System.out.println("Cancel is clicked"); } File selectedFile = chooser.getSelectedFile();File currentDirectory = chooser.getCurrentDirectory();

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Applying a File Filter A file filter may be used to restrict the listing in JFileChooser to only those files/directories that meet the designated filtering criteria. To apply a file, we define a subclass of the javax.swing.filechooser.FileFilter class and provide the accept and getDescription methods. public boolean accept(File file) public String getDescription( ) See the JavaFilter class that restricts the listing to directories and Java source files.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Low-Level File I/O To read data from or write data to a file, we must create one of the Java stream objects and attach it to the file. A stream is a sequence of data items, usually 8-bit bytes. Java has two types of streams: an input stream and an output stream. An input stream has a source form which the data items come, and an output stream has a destination to which the data items are going.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Streams for Low-Level File I/O FileOutputStream and FileInputStream are two stream objects that facilitate file access. FileOutputStream allows us to output a sequence of bytes; values of data type byte. FileInputStream allows us to read in an array of bytes.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Sample: Low-Level File 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 outStream.close();

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Sample: Low-Level File 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++) { System.out.println(byteArray[i]); } //input done, so close the stream inStream.close();

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Streams for High-Level File I/O FileOutputStream and DataOutputStream are used to output primitive data values FileInputStream and DataInputStream are used to input primitive data values To read the data back correctly, we must know the order of the data stored and their data types

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Setting up DataOutputStream A standard sequence to set up a DataOutputStream object: File outFile = new File( "sample2.data" ); FileOutputStream outFileStream = new FileOutputStream(outFile); DataOutputStream outDataStream = new DataOutputSteam(outFileStream);

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Sample Output import java.io.*; class Ch12TestDataOutputStream { public static void main (String[] args) throws IOException {... //set up outDataStream //write values of primitive data types to the stream outDataStream.writeInt( ); outDataStream.writeLong( L); outDataStream.writeFloat( F); outDataStream.writeDouble( D); outDataStream.writeChar('A'); outDataStream.writeBoolean(true); //output done, so close the stream outDataStream.close(); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Setting up DataInputStream A standard sequence to set up a DataInputStream object: File inFile = new File( "sample2.data" ); FileOutputStream inFileStream = new FileOutputStream(inFile); DataOutputStream inDataStream = new DataOutputSteam(inFileStream);

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Sample Input import java.io.*; class Ch12TestDataInputStream { public static void main (String[] args) throws IOException {... //set up inDataStream //read values back from the stream and display them System.out.println(inDataStream.readInt()); System.out.println(inDataStream.readLong()); System.out.println(inDataStream.readFloat()); System.out.println(inDataStream.readDouble()); System.out.println(inDataStream.readChar()); System.out.println(inDataStream.readBoolean()); //input done, so close the stream inDataStream.close(); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Reading Data Back in Right Order The order of write and read operations must match in order to read the stored primitive data back correctly. outStream.writeInteger(…); outStream.writeLong(…); outStream.writeChar(…); outStream.writeBoolean(…); inStream.readInteger(…); inStream.readLong(…); inStream.readChar(…); inStream.readBoolean(…);

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Textfile Input and Output Instead of storing primitive data values as binary data in a file, we can convert and store them as a string data. –This allows us to view the file content using any text editor To output data as a string to file, we use a PrintWriter object To input data from a textfile, we use FileReader and BufferedReader classes –From Java 5.0 (SDK 1.5), we can also use the Scanner class for inputting textfiles

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Sample Textfile Output import java.io.*; class Ch12TestPrintWriter { public static void main (String[] args) throws IOException { //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( ); outStream.println("Hello, world."); outStream.println(true); //output done, so close the stream outStream.close(); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Sample Textfile Input import java.io.*; class Ch12TestBufferedReader { public static void main (String[] args) throws IOException { //set up file and stream File inFile = new File("sample3.data"); FileReader fileReader = new FileReader(inFile); BufferedReader bufReader = new BufferedReader(fileReader); String str; str = bufReader.readLine(); int i = Integer.parseInt(str); //similar process for other data types bufReader.close(); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Sample Textfile Input with Scanner import java.io.*; class Ch12TestScanner { public static void main (String[] args) throws IOException { //open the Scanner Scanner scanner = new Scanner(new File("sample3.data")); //get integer int i = scanner.nextInt(); //similar process for other data types scanner.close(); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 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 {... }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Reading 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 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 ); //read the array Person[ ] people = (Person[]) inObjectStream.readObject( );

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Problem Statement Write a class that manages file I/O of an AddressBook object.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Development Steps We will develop this program in four steps: 1.Implement the constructor and the setFile method. 2.Implement the write method. 3.Implement the read method. 4.Finalize the class.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 1 Design We identify the data members and define a constructor to initialize them. Instead of storing individual Person objects, we will deal with a AddressBook object directly using Object I/O techniques.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 1 Code Directory: Chapter12/Step1 Source Files: AddressBookStorage.java TestAddressBookStorage.java Directory: Chapter12/Step1 Source Files: AddressBookStorage.java TestAddressBookStorage.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 1 Test We include a temporary output statement inside the setFile method. We run the test main class and verify that the setFile method is called correctly.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 2 Design Design and implement the write method The data member filename stores the name of the object file to store the address book. We create an ObjectOutputStream object from the data member filename in the write method. The write method will propagate an IOException when one is thrown.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 2 Code Directory: Chapter12/Step2 Source Files: AddressBookStorage.java TestAddressBookWrite.java Directory: Chapter12/Step2 Source Files: AddressBookStorage.java TestAddressBookWrite.java

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 2 Test We run the test program several times with different sizes for the address book. We verify that the resulting files indeed have different sizes. At this point, we cannot check whether the data are saved correctly or not. –We can do so only after finishing the code to read the data back.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 3 Design Design and implement the read method. The method returns an AddressBook object read from a file (if there's no exception) The method will propagate an IOException when one is thrown.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 3 Code Directory: Chapter12/Step3 Source Files: AddressBookStorage.java TestAddressBookRead.java Directory: Chapter12/Step3 Source Files: AddressBookStorage.java TestAddressBookRead.java

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 3 Test We will write a test program to verify that the data can be read back correctly from a file. To test the read operation, the file to read the data from must already exist. We will make this test program save the data first by using the TestAddressBookWrite class from.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 4: Finalize We perform the critical review of the final program. We run the final test