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.

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.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
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.
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.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
Files and Streams CS 21a. 10/02/05 L18: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L07 (Chapter 18) Binary I/O.
File I/O There’s more to life than the keyboard. Interactive vs. file I/O All of the programs we have seen or written thus far have assumed interaction.
©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.
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.
13-Jul-15 Simple Java I/O Part I General Principles.
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.
Files and Streams 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
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.
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.
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.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Java Chapter 9 File Input and Output. Objectives In this chapter you will: Learn how bits, characters, records, and files fit into a data hierarchy Explore.
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.
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.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
Chapter - 11 Introduction to File and Streams This chapter includes -  Defining a File  Testing and Checking File Objects  Accessing File Objects.
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.
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.
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.
Introduction to OOP with Java 4th Ed, C. Thomas Wu
OO Design and Programming II I/O: Reading and Writing
File - CIS 1068 Program Design and Abstraction
CMSC 202 Text File I/O.
CS1101: Programming Methodology
I/O Basics.
Chapter 12 File Input and Output
MSIS 670: Object-Oriented Software Engineering
File Input and Output.
Presentation transcript:

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 data at a keyboard and sees output on a screen We can also receive data from, or send data to, the secondary storage devices on the computer This type of input and output is called file I/O

File I/O 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. Both of these actions involve interacting with the operating system and its file structure

The file concept We can envision a file as a special kind of container that can hold a collection of data or instructions A file can also contain a collection of other files: such a file is called a directory or folder An important point to remember is that Java considers a folder to be just another file

File system organization Under Windows and most other modern operating systems, information is stored on disk in a hierarchically ordered structure consisting of directories, subdirectories, and files Disks are designated using letters – for example, C is typically the computer’s hard drive (or its primary partition), while A is traditionally a floppy disk The Windows GUI portrays directories as folders, which can contain other folders or files

Windows file system example The illustration below depicts a typical file system structure under Windows

Opening a file for input or output 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. –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. We do this by calling a File constructor

Opening a file The simplest syntax for opening a file is: File aFile = new File (“filename”); –The String argument designates the name of the file (as seen by the operating system) –This syntax assumes that the argument is the name of a file (not a folder), and that the file is located in the same folder as the program’s code file

Opening a file Slightly more complicated syntax is necessary if the file to be opened is in a different folder: File aFile = new File (“path”, “file”); –The first argument specifies the disk and file system hierarchy that contains the file –For example, if the file is in directory G:\shared\cate\cs1, you would write: File aFile = new File (“g:/shared/cate/cs1”, “file”); Note the use of the forward slash; you can use either this format or: File aFile = new File (“g:\\shared\\cate\\cs1”, “file”);

Opening a file A File object may also be associated to a directory. As far as Java is concerned, a directory is just a special kind of file The code on the next slide illustrates the use of a File object to open a directory, then list the names of all the files in the directory

Example File directory = new File (“C:/JavaPrograms/Ch12”); String filename[] = directory.list(); // Returns an array of strings naming the files and // directories in the directory denoted by this pathname for (int i=0; i<filename.length; i++){ System.out.println(filename[i]); }

File methods The previous slide illustrated the use of the list() method, which returns an array of Strings containing the names of files within a directory Several other useful methods of the File class are listed in the Java API; we will examine a few of these

File methods 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 } It is particularly useful to check input files to see if they actually exist before we try to read from them

File methods To determine if a File object is associated to a file or directory, we call its boolean method isFile. A similar method, isDirectory, returns true if the File object is associated with a folder instead of an ordinary file.

Choosing a file from a list A javax.swing.JFileChooser object allows the user to select a file from a list of available files. The code fragment below illustrates how this is done: JFileChooser chooser = new JFileChooser();... chooser.showOpenDialog(null);

A JFileChooser object displayed with the showOpenDialog method

JFileChooser Object methods The getSelectedFile method retrieves the desired file. The getName and getAbsolutePath methods retrieve the name and full path of a selected file (similar methods exist for File objects). The showSaveDialog method displays a JFileChooser with a Save button.

A JFileChooser object displayed with the showSaveDialog method

JFileChooser Example The next couple of slides display a program that uses JFileChooser objects to display a list of files, then allow the user to choose which file should be open for output Note the use of File and JFileChooser methods in the code

import java.io.*; import javax.swing.*; public class TestJFileChooser { 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(); 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); 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"); }

Sample output from running the TestJFileChooser program

Reading and Writing Files 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. 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.

Reading and Writing Files An input stream has a source from which the data items come, and an output stream has a destination to which the data items are going. 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.

Writing Data to a File To send output to a file, do the following: –Create and open a File object File output = new File(“C:/datafiles”, “stuff”); –Associate a new FileOutputStream object with the File object FileOutputStream outs = new FileOutputStream(output); –Write the desired data to the FileOutputStream object byte [] snacks = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; outs.write(snacks); –Close the File stream outs.close();

The importance of closing a file If the stream object is not closed, then data may get lost due to data caching 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.

The importance of closing a file 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.

Reading Data from a File To read data into a program, we reverse most of the steps in the output routine. We use the read method of FileInputStream to read in an array of bytes. First we create a FileInputStream object: File inFile = new File(“sample1.data”); FileInputStream inStream = new FileInputStream(inFile); Then we must declare and create an array to hold the data: int filesize = (int) inFile.length(); byte[] byteArray = new byte[filesize];

Reading Data from a File 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 the array of bytes: inStream.read(byteArray);

Low-level File I/O The read and write methods of the FileInputStream and FileOutputStream classes read and write entire arrays of bytes, as we have seen 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.

High-level File I/O Using DataOutputStream allows us to output Java primitive data type values by converting the values into a sequence of bytes. The argument to the DataOutputStream constructor is a FileOutputStream object. A DataOutputStream object does not get connected to a file directly; instead, its role is to provide high-level access to a file by handling the data type conversions.

Relationship between File and output Stream objects

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.

Relationship between File object and input Stream objects

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. Data may be stored in ASCII format instead of binary format – this requires the use of a different set of objects

High-Level File I/O With ASCII format, all data are converted to string data. A file whose contents are stored in ASCII format is called a text file. To generate a textfile we use a PrintWriter is an object. PrintWriter supports only two output methods, which should look familiar: –print –println (for print line)

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.

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. File inFile = new File(“sample3.data”); FileReader fileReader = new FileReader(inFile); BufferedReader brdr = new BufferedReader(fileReader); –Then we read data, using the readLine method of BufferedReader. String str = bufReader.readLine(); –Finally, we convert the String to a primitive data type as necessary (using wrapper classes as we’ve done before).

File I/O and Objects To write objects to a file, we use ObjectOutputStream. To read objects from a file, we use ObjectInputStream.

File I/O and Objects 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. We modify the definition by adding the phrase implements Serializable to it. import java.io.*; class Person implements Serializable { // the rest is the same }

File I/O and Objects 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);

File I/O and Objects To save a Person object, we execute: Person person = new Person(“Mr. Man”, 20, ‘M’); outObjectStream.writeObject (person ); 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.

File I/O and Objects 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.

File I/O and Objects The readObject method can throw a ClassNotFoundException (wrong type casting) in addition to an IOException. Either exception may be caught or propagated. If a file contains objects from different classes, they must be read in the correct order and the matching type casting must be applied.