Files and Streams. Midterm exam Time: Wednesday, October 31, 2007 Format: Multiple choices (about 15 to 20 questions) Determine the results of the code.

Slides:



Advertisements
Similar presentations
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.
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.
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.
Files Files are used to store long term data. –Typically referred to as persistent data. –A file is a group of related records. –A list of friends addresses.
© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter Chapter 11 File Input and Output.
Files & Streams. Files Introduction Files are used for long-term retention of large amounts of data, even after the program that created the data terminates.
©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.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12 File Input and Output.
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.
© The McGraw-Hill Companies, 2006 Working with files Chapter 20.
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.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Files and Streams (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Files and Streams 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
1 Chapter 15 – Files I/O basics File I/O Classes File I/O Basic Operations Text File Output PrintWriter import Statement with a * Text File Input Scanner,
CIS 270—Application Development II Chapter 14—Files and Streams.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Chapter 15 – Files I/O basics File I/O Classes File I/O Basic Operations Text File Output PrintWriter import Statement with a * Text File Input Scanner,
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.
Binary Files, Random Access Files Binary Files The way data is stored in memory is sometimes called the raw binary format. Data can be stored in.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Files and Streams Chapter What You Will Learn Create files Read files Write files Update files.
Introduction to Programming G50PRO University of Nottingham Unit 11 : Files Input/Ouput Paul Tennent
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.
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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
Chapter 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
 Pearson Education, Inc. All rights reserved Files and Streams.
Object Serialization. Sequential-access Text Files Sequential-access files store records In order by the record-key field Java imposes no structure on.
1 Exceptions Exception handling – Exception Indication of problem during execution – E.g., divide by zero – Chained exceptions Uses of exception handling.
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.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
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.
 Pearson Education, Inc. All rights reserved Files and Streams.
Java Programming, Second Edition Chapter Sixteen File Input and Output.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
 2005 Pearson Education, Inc. All rights reserved Files and Streams.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Recitation File I/O. File I/O File inFile = new File("data.txt"); File inFile = new File (“/Users/sunil/test.txt");
Ch14 Files and Streams OBJECTIVES
CS1101: Programming Methodology
I/O Basics.
Chapter 12 File Input and Output
MSIS 670: Object-Oriented Software Engineering
14 Files and Streams.
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
14 Files and Streams.
Chapter 15 Files, Streams and Object Serialization
Presentation transcript:

Files and Streams

Midterm exam Time: Wednesday, October 31, 2007 Format: Multiple choices (about 15 to 20 questions) Determine the results of the code Writing a piece of code Cover: Fundamental of Java, Array, Search and Sort, String, Error handling

Introduction Storage of data in variables and arrays is temporary Files used for long-term retention of large amounts of data, even after the programs that created the data terminate Persistent data – exists beyond the duration of program execution Why is File I/O important?

Review The following two statements will associate file 1 and file 2 to the same file: File file1=new File(“c:\\one\\two”,”three.dat”); File file2 = new File(“c:\\one\\two\\three.dat”); a. True b. False

Review The following two statements will associate file 1 and file 2 to the same file: File file1=new File(“c:\\one\\two”,”three.dat”); File file2 = new File(c:\\one\\two\\three.dat”); a. True b. False

Review The following two statements will associate file 1 and file 2 to the same file: File file1=new File(“c:\\one\\two”,”three.dat”); File file2 = new File(c:\\one\\two\\three.dat”); a. True b. False

Review Complete a code fragment that will create a File object and associate it to an existing file named mydata.dat in the Programs directory of a windows network P: drive = File(“ \\ \\ “); a. P: b. mydata.dat c. file d. Programs e. new f. File

Review Complete a code fragment that will create a File object and associate it to an existing file named mydata.dat in the Programs directory of a windows network P: drive = File(“ \\ \\ “); a. P: b. mydata.dat c. file d. Programs e. new f. File FCE ADB

Java and File Input/Output Files stored on secondary storage devices Stream – ordered data that is read from or written to a file Java views each files as a sequential stream of bytes

Files and Streams Operating system provides mechanism to determine end of file End-of-file marker Count of total bytes in file Java program processing a stream of bytes receives an indication from the operating system when program reaches end of stream

Files and Streams File streams Byte-based streams – stores data in binary format Binary files – created from byte-based streams, read by a program that converts data to human-readable format Character-based streams – stores data as a sequence of characters Text files – created from character-based streams, can be read by text editors

Files and Streams Java opens file by creating an object and associating a stream with it Standard streams: System.in – standard input stream object System.out – standard output stream object, System.err – standard error stream object

Files and Streams java.io classes FileInputStream and FileOutputStream – byte-based I/O FileReader and FileWriter – character- based I/O ObjectInputStream and ObjectOutputStream – used for input and output of objects or variables of primitive data types File – useful for obtaining information about files and directories

Files and Streams Classes Scanner and Formatter Scanner – can be used to easily read data from a file Formatter – can be used to easily write data to a file (needs j2se 5.0 to run)

Java’s view of a file of n bytes.

Overview of old knowledge of File I/O Low level I/OHigh level I/OText file I/O Treat a file As a set of bytes Treat A file As a set of data of primitive Data type Treat A file As a set of text (or String)

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.

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.

Low level data input Step 1: Create a File object Step 2: Create a FileInputStream objectFileInputStream Step 3: Declare an array to keep input data, allocate memory for this array Step 4: Read data and process data if neededRead data Step 5: Close the file

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

Low level data output Step 1: Create a File object Step 2: Create a FileOutputStream objectFileOutputStrea Step 3:Get data ready Step 4:Write data to output streamWrite data Step 5: Close the file

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

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

Setting up DataOutputStream A standard sequence to set up a DataOutputStream object:

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

Setting up DataInputStream A standard sequence to set up a DataInputStream object:

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

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.

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

Read data from a text file Step 1: Create a File object Step 2: Create a FileReader objectFileReader Step 3: Create a BufferedReader objectBufferedReader Step 4: Read line by line Step 5: Convert String object to primitive data type as necessary Step 6: Close the file

Create FileReader and BufferedReader objects How to create a FileReader ojbect: FileReader = new FileReader( ); How to create a BufferedReaderobject: BufferedReader = new BufferedReader(<name of a FileReader object); How to read a line.readLine();

Write data to a text file Step 1: Create a File object Step 2: Create a FileOutputStream objectFileOutputStream Step 3: Create a PrintWriter objectPrintWrite Step 4: Write line(s) Step 5: Close the file

Create a FileOutputSTream and PrintWriter objects How to create a FileOutputStream objects: FileOutputStream = new FileOutputStream( ); How to create a PrintWriter object PrintWriter = new PrintWriter( ); How to write a string to a file.println( ); More details on this link

Example import java.io.*; public class OutputExample{ public static void main (String[] args) throws IOException { File inFile = new File("e:\\Temp\\output.dat"); FileOutputStream fileStream = new FileOutputStream(inFile); PrintWriter printWriter = new PrintWriter(fileStream); String inputStr; int number[] = new int[10]; for (int i=0;i<number.length; i++) { number[i] = i+1; printWriter.println(number[i]); } printWriter.close(); System.exit(0); }

Example import java.io.*; public class OutputExample{ public static void main (String[] args) throws IOException { File inFile = new File("e:\\Temp\\output.dat"); FileOutputStream fileStream = new FileOutputStream(inFile); PrintWriter printWriter = new PrintWriter(fileStream); String inputStr; int number[] = new int[10]; for (int i=0;i<number.length; i++) { number[i] = i+1; printWriter.println(number[i]); } printWriter.close(); System.exit(0); } Step 1-3

Example import java.io.*; public class OutputExample{ public static void main (String[] args) throws IOException { File inFile = new File("e:\\Temp\\output.dat"); FileOutputStream fileStream = new FileOutputStream(inFile); PrintWriter printWriter = new PrintWriter(fileStream); String inputStr; int number[] = new int[10]; for (int i=0;i<number.length; i++) { number[i] = i+1; printWriter.println(number[i]); } printWriter.close(); System.exit(0); } Step 4 (in for loop)

Example import java.io.*; public class OutputExample{ public static void main (String[] args) throws IOException { File inFile = new File("e:\\Temp\\output.dat"); FileOutputStream fileStream = new FileOutputStream(inFile); PrintWriter printWriter = new PrintWriter(fileStream); String inputStr; int number[] = new int[10]; for (int i=0;i<number.length; i++) { number[i] = i+1; printWriter.println(number[i]); } printWriter.close(); System.exit(0); } Step 5 (close file)

File Input and Output Sequential-access files Random-access files

Sequential-Access Text Files Each line describes a record in a database. Records are stored in order by record-key field Can be created as text files or binary files Input files: Programmer must structure files Output files: Formatter class can be used to open a text file for writing

Create a text file using Formatter class Step 1: Pass name of file to constructor If file does not exist, will be created If file already exists, contents are truncated (discarded) Step 2: Use method format to write formatted text to file Step 3: Use method close to close the Formatter object (if method not called, OS normally closes file when program exits)

Practice Step 1: Create a package called Lab7 under your Labs project. Select Lab7 package -> New class -> AccountRecord. Then cut and paste the content of AccountRecord.java in D2L to this AccountRecord class. Step 2: Select Lab7 package -> New class -> CreateTextFile. Then cut and paste the content of CreateTextFile class in D2L to this newly created class. Step 3. Select Lab7 package -> New class -> CreateTextFileMain class.

Practice Step 4: In CreateTextFileMain class, add the main method, in which you should: - create a CreateTextFile object - using this object to open a file, add records and write to a file.

End-of-file key combinations for various popular operating systems.

Reading Data from a Sequential- Access Text File Data is stored in files so that it may be retrieved for processing when needed Scanner object can be used to read data sequentially from a text file Pass File object representing file to be read to Scanner constructor FileNotFoundException occurs if file cannot be found Data read from file using same methods as for keyboard input – nextInt, nextDouble, next, etc. IllegalStateException occurs if attempt is made to read from closed Scanner object

Practice Step 1: Under your Lab7 package, create a new class ReadTextFile. Then cut and paste the content of ReadTextFile.java in D2L to this class. Step 2: Select Lab7 package -> New class -> ReadTextFileMain class. In this class, you should create a ReadTextFile object - using this object to open a file, read records from a text file and close that file.

Updating Sequential-Access Files Data in many sequential files cannot be modified without risk of destroying other data in file Old data cannot be overwritten if new data is not same size Records in sequential-access files are not usually updated in place. Instead, entire file is usually rewritten.

Practice Exercise for Midterm exam

Random-Access Files Sequential-access files inappropriate for instant-access applications Instant-access applications are applications in which desired information must be located immediately Instant access possible with random-access files (also called direct-access files) and databases

Random-Access Files Data can be inserted in random-access file without destroying other data Different techniques for creating random-access files Simplest: Require that all records in file be same fixed length Easy to calculate (as a function of record size and record key) exact location of any record relative to beginning of file

Java’s view of a random- access file.

Creating a Random-Access File RandomAccessFile class Includes all capabilities of FileInputStream and FileOutputStream Includes capabilities for reading and writing primitive-type values, byte arrays and strings Using RandomAccessFile, program can read or write data beginning at location specified by file-position pointer

Creating a Random-Access File RandomAccessFile class Manipulates all data as primitive types Methods readInt, readDouble, readChar used to read integer, double and character data from file Methods writeInt, writeDouble, writeChars used to write integer, double and string data to file File-open mode – specifies whether file is opened for reading ( “r” ), or for both reading and writing ( “rw” ). File- open mode specified as second argument to RandomAccessFile constructor

Practice Step 1: Create a package called Lab7 under your Labs project. Select Lab7 package -> New class -> RandomAccessAccountRecord. Then cut and paste the content of RandomAccessAccountRecord.java in D2L to this class. Step 2: Select Lab7 package -> New class -> CreateRandomFile. Then cut and paste the content of CreateRandomFile class in D2L to this newly created class. Step 3. Select Lab7 package -> New class -> CreateRandomFileMain class.

Practice Step 4: In CreateRandomFileMain class, add the main method, in which you should: - create a CreateRandomFile object - using this object to create a file.

Writing Data Randomly to a Random- Access File RandomAccessFile method seek positions file-position pointer to a specific location in a file relative to beginning of file Size of each record is known, so location in file of a specific record can be found by multiplying size of record with number of record

Writing Data Randomly to a Random- Access File Once location known, new record data can be written without worrying about rest of file, as each record is always same size

Practice Step 1: Select Lab7 package -> New class -> WriteRandomFile. Then cut and paste the content of WriteRandomFile class in D2L to this newly created class. Step 3. Select Lab7 package -> New class -> WriteRandomFileMain class in which we - create a WriteRandomFile object - using this object to open file, add records and write to a random-access file.

Reading Data Sequentially from a Random-Access File Open file with “r” file-open mode for reading Ignore empty records (usually those with account number of zero) when reading from file

Reading Data Sequentially from a Random-Access File Records stored by account number in random-access files have added bonus of being sorted, as each record’s data can only be placed in specific portion of file Sorting with direct-access techniques is blazingly fast—speed achieved by making file large enough to hold every possible record Space/time trade-off