Chapter 12 File Input and Output

Slides:



Advertisements
Similar presentations
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.
Advertisements

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 12 File Input and Output Animated Version.
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.
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.
CSSE221 Section 2.  Using JFileChooser to ease use of file I/O in GUI programs  Review of text-based file I/O  Streams/Readers/Writers  Using the.
©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.
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.
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.
©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.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
15-Jul-15 Simple Java I/O Part I General Principles.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
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.
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.
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.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
Program data (instance variables, local variables, and parameters) is transient, because its lifetime ends with the program...if not, before. Sometimes.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
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.
CHAPTER 15 STREAMS. CHAPTER GOALS To be able to read and write files To become familiar with the concepts of text and binary files To be able to read.
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.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
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.
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.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Project 6 due on Thursday March 31 (3 weeks)
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.
Recitation File I/O. File I/O File inFile = new File("data.txt"); File inFile = new File (“/Users/sunil/test.txt");
Java IO Exploring the java.io package and living to talk about it.
java.io supports console and file I/O
Introduction to OOP with Java 4th Ed, C. Thomas Wu
OO Design and Programming II I/O: Reading and Writing
CMSC 202 Text File I/O.
Ch14 Files and Streams OBJECTIVES
CS1101: Programming Methodology
OBJECT ORIENTED PROGRAMMING II LECTURE 21_1 GEORGE KOUTSOGIANNAKIS
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Chapter 17 Binary I/O 1.
Accessing Files in Java
Part I General Principles
Streams and File I/O Chapter 9 Chapter 9.
Defining Your Own Classes
MSIS 670: Object-Oriented Software Engineering
OBJECT ORIENTED PROGRAMMING II LECTURE 11_1 GEORGE KOUTSOGIANNAKIS
David Davenport Spring 2005
Presentation transcript:

Chapter 12 File Input and Output ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

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

Chapter 12 Objectives, cont. After you have read and studied this chapter, you should be able to 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.1 File and JFileChooser Objects The action of saving, or writing, data to a file is called file output. The action of reading data from a file is called file input. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.1 File and JFileChooser Objects Before we can read data from a file, we must create a File object and associate it to the file from which we wish to read. We do this by calling a File constructor: File inFile = newFile(“sample.data”); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.1 File and JFileChooser Objects This approach assumes that the file is located in the current directory. Otherwise, we must specify the path and file name when we call the constructor: File inFile = new File(“C:/JavaPrograms”,”xyz.data”); The formatting of the path name and file name is different for different operating systems. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 12.1 Directory structure used for the examples in this section. We assume the Windows environment. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.1 File and JFileChooser Objects We can check if a File object is associated correctly to an existing file by calling its exists method: if (inFile.exists()){ //inFile is associated correctly to //an existing file } else { //inFile is not associated to any //existing file } ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.1 File and JFileChooser Objects When a valid association is established, we say a file is opened. A file must be opened before we can do any input and output to the file. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.1 File and JFileChooser Objects A File object may also be associated to a directory. File directory = new File (“C:/JavaPrograms/Ch12”); String filename[] = directory.list(); for (int i=0; i<filename.length; i++){ System.out.println(filename[i]); } ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.1 File and JFileChooser Objects To determine if a File object is associated to a file or directory, we call its boolean method isFile. A javax.swing.JFileChooser object allows the user to select a file. JFileChooser chooser = new JFileChooser(); ... chooser.showOpenDialog(null); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 12.2 A sample JFileChooser object displayed with the showOpenDialog method. The dialog title and the okay button are labeled Open. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.1 File and JFileChooser Objects The getSelectedFile method retrieves the desired file. The getName and getAbsolutePath methods retrieve the name and full path of a selected file. The showSaveDialog method displays a JFileChooser with a Save button. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 12.3 A sample JFileChooser object displayed with the showSaveDialog method. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.1 File and JFileChooser Objects /* File: TestJFileChooser.java */ import java.io.*; import javax.swing.*; class Ch12TestJFileChooser { public static void main (String[] args) { JFileChooser chooser; File file, directory; int status; chooser = new JFileChooser( ); status = chooser.showOpenDialog(null); if (status == JFileChooser.APPROVE_OPTION) { file = chooser.getSelectedFile(); directory = chooser.getCurrentDirectory(); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.1 File and JFileChooser Objects System.out.println("Directory: " + directory.getName()); System.out.println("File selected to open: " + file.getName()); System.out.println("Full path name: " + file.getAbsolutePath()); } else { JOptionPane.showMessageDialog(null, "Open File dialog canceled"); } System.out.println("\n\n"); status = chooser.showSaveDialog(null); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.1 File and JFileChooser Objects if (status == JFileChooser.APPROVE_OPTION) { file = chooser.getSelectedFile(); directory = chooser.getCurrentDirectory(); System.out.println("Directory: " + directory.getName()); System.out.println("File selected for saving data: " + file.getName()); System.out.println("Full path name: " + file.getAbsolutePath()); } else { JOptionPane.showMessageDialog(null, "Save File dialog canceled"); } ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 12.4 A sample output from running the Ch12TestJFileChooser program once. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.1 File and JFileChooser Objects A file filter may be used to remove unwanted files from the list. 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( ) ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.1 File and JFileChooser Objects The accept method returns true if the parameter file is a file to be included in the list. The getDescription method returns a text that will be displayed as one of the entries for the “Files of Type:” drop-down list. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.1 File and JFileChooser Objects When the filter class is defined, we can set it to a file chooser to restrict the listing to the desired directories and files. JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new JavaFilter(()); int status = chooser.showOpenDialog(null); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.2 Low-Level File I/O Once a file is opened by associating a File object to it, we can access the file. 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.2 Low-Level File I/O 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

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

12.2 Low-Level File I/O We will process the following byte array: byte[] byteArray = {10, 20, 30, 40, 50, 60, 70, 80}; We create a File object: File outFile = new File (“sample1.data”); Associate a new FileOutputStream object to outFile: FileOutputStream outStream = new FileOutputStream(outFile); and write the whole byte array at once to the file: outstream.write(byteArray); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.2 Low-Level File I/O After the values are written to the file, we must close the stream: outStream.close(); If the stream object is not closed, then data may get lost due to data caching. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.2 Low-Level File I/O Data is saved in blocks of bytes to reduce the time it takes to save all of our data. The operation of saving data as a block is called data caching. To carry out data caching, part of memory is reserved as a data buffer or cache, which is used as a temporary holding place. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.2 Low-Level File I/O Data are first written to a buffer. When the buffer becomes full, the data in the buffer are actually written to a file. If there are any remaining data in the buffer and the file is not closed, those data will be lost. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.2 Low-Level File I/O To read data into a program, we reverse the steps in the output routine. We use the read method of FileInputStream to read in an array of bytes. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.2 Low-Level File I/O First we create a FileInputStream object: File inFile = new File(“sample1.data”); FileInputStream inStream = new FileInputStream(inFile); Then we must declare and create byteArray: int filesize = (int) inFile.length(); byte[] byteArray = new byte[filesize]; ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.2 Low-Level File I/O We use the length method of the File class to determine the size of the file. This allows us to create an array of bytes whose size is the size of the file. Finally, we read the data into an array of bytes: inStream.read(byteArray); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.2 Low-Level File I/O We can output data other than bytes if we can type cast them into bytes. To read the data back, we use the read method. Depending on the data type we converted the data from, we may need to type cast back into the original data type. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.3 High-Level File I/O Using DataOutputStream allows us to output Java primitive data type values. A DataOutputStream object will convert the primitive data type values into a sequence of bytes. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.3 High-Level File I/O The argument to the DataOutputStream constructor is a FileOutputStream object. A DataOutputStream object does not get connected to a file directly. The role of a DataOutputStream object is to provide high-level access to a file by handling the data type conversions. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 12.5 A diagram showing how the three objects outFile, outFileStream, and outDataStream are related. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.3 High-Level File I/O To read data back from the file, we reverse the operation. We use three objects: File, FileInputStream, and DataInputStream. Data must be read in the order in which it was written; otherwise, the results will be unpredictable. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 12.6 A diagram showing how the three objects inFile, inFileStream, and inDataStream are related. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 12.7 The order of write and read operations must match to read the stored data back correctly. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.3 High-Level File I/O FileOutputStream and DataOutputStream objects produce a binary file in which the contents are stored in the format (binary format) in which they are stored in the main memory. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.3 High-Level File I/O Data may be stored in ASCII format instead of binary format. With ASCII format, all data are converted to string data. A file whose contents are stored in ASCII format is called a text file. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.3 High-Level File I/O PrintWriter is an object we use to generate a textfile. PrintWriter supports only two output methods: print println (for print line) ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.3 High-Level File I/O An argument to the methods may be any primitive data type. The methods convert the parameter to string and output this string value. The constructor of PrintWriter, like that of DataOutputStream, requires an output stream as its argument. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.3 High-Level File I/O To read data from a text file, we use the FileReader and BufferedReader objects. We first associate a BufferedReader object to a file. Then we read data, using the readLine method of BufferedReader. Finally, we convert the String to a primitive data type as necessary. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.3 High-Level File I/O File inFile = new File(“sample3.data”); FileReader fileReader = new FileReader(inFile); BufferedReader bufReader = new BufferedReader(fileReader) String str = bufReader.readLine(); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.4 Object I/O We can now store objects just as we can store primitive data values. To write objects to a file, we use ObjectOutputStream. To read objects from a file, we use ObjectInputStream. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.4 Object I/O In this example, we will write Person objects to a file. The first step is to modify the Person class definition to allow ObjectOutputStream and ObjectInputStream to perform object I/O. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.4 Object I/O We modify the definition by adding the phrase implements Serializable to it. import java.io.*; class Person implements Serializable { //the rest is the same } There are no methods for us to define in the implementation class. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.4 Object I/O To save objects to a file, we first create an ObjectOutputStream object: File outFile = new File(“objects.dat”); FileOutputStream outFileStream = new FileOutputStream(outFile); ObjectOutputStream outObjectStream = new ObjectOutputStream(outFileStream); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.4 Object I/O To save a Person object, we execute Person person = new Person(“Mr. Espresso”, 20, ‘M’); outObjectStream.writeObject(person); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.4 Object I/O Different types of objects may be saved to a single file. We can also mix objects and primitive data type values in the same file. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.4 Object I/O To read objects from a file, we use FileInputStream and ObjectInputStream. We use the method readObject to read an object. Because we can store any types of objects to a single file, we must type cast the object read from the file. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.4 Object I/O The readObject method can throw a ClassNotFoundException (wrong type casting) in addition to an IOException. Either exception may be caught or propagated. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

12.4 Object I/O If a file contains objects from different classes, they must be read in the correct order and the matching type casting must be applied. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.