CS 116 Object Oriented Programming II Lecture 11 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.

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

Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
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.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
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.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS 1 Copyright: FALL 2014 Illinois Institute of Technology_ George Koutsogiannakis.
©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.
1 File Output. 2 So far… So far, all of our output has been to System.out  using print(), println(), or printf() All input has been from System.in 
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 12 File Input and Output.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
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.
Exceptions and Input/Output Operations
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
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.
CIS 068 JAVA I/O: Streams and Files. CIS 068 I/O Usual Purpose: storing data to ‘nonvolatile‘ devices, e.g. harddisk Classes provided by package java.io.
Chapter 10 Exceptions and File I/O. © 2004 Pearson Addison-Wesley. All rights reserved10-2 Exceptions Exception handling is an important aspect of object-oriented.
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.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
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.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
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 Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Lecture 5 I/O and Parsing
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
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.
Chapter 11 Exceptions and Input/Output Operations.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
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.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
File Input and Output Appendix E © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that.
GENERICS AND FILE HANDLING Saumya Srivastava (977934) Divyangana Pandey (977790) Shubhi Saxena (978108) Arka Das (962969) AHD05/15-16 AJA 21.
Java Input / Output l a modular approach to input/output: - different stream objects are connected/wrapped to handle I/O l a data stream object: a flow.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
Java I/O 1. Java I/O (Input and Output) is used to process the input and produce the output based on the input. The java.io package contains all the classes.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
For Friday Finish reading chapter 9 WebCT quiz 17.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
OO Design and Programming II I/O: Reading and Writing
OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS
Lesson 8: More File I/O February 5, 2008
OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 21_1 GEORGE KOUTSOGIANNAKIS
I/O Basics.
CS 116 Object Oriented Programming II
Streams and File I/O Chapter 14.
CHAPTER 5 (PART 2) JAVA FILE INPUT/OUTPUT
OBJECT ORIENTED PROGRAMMING II LECTURE 11_1 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 13_1 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Web Design & Development Lecture 8
File Input and Output.
Lecture 18 File I/O CSE /5/2019.
Presentation transcript:

CS 116 Object Oriented Programming II Lecture 11 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer

Today’s Topics The java.io Package Reading Text Files Reading Structured Text Files Reading files using Input Streams 2

File Types Java basically supports two types of files: Text files (human readable): data is stored as characters Binary files: data is stored as raw bytes (1s and 0s) E.g. executable files, image files The type of a file determines the Java API classes for writing to the file. Input to the file can be: Files written using Bytes Streams (1s and 0s). Files written using Character Streams (char types). Files written in terms of Strings (text). 3

File Types Input to the file can be: (cont.) Files written using primitive data types (int, double etc) Files written using entire object streams (recording all information about an object in a coded format). To read an existing file, you must know the file's type in order to select and import the appropriate library classes for reading the file. 4

Reading Text Files with Scanner import java.io.File; import java.io.IOException; import java.util.Scanner; Public class ReadFile { Public static void main(String[] args) { try{ File myfile=new File(“mytextfiel.txt”); Scanner scan=new Scanner(myfile); while(scan.hasMoreTokens()) { String str=scan.next(); System.out.println(str); } 5 catch)(IOException ioe){ System.out.println(ioe.t oString()); } } Text files are human readable Lines of tokens separated by a delimiter (default delimiter: space)

Streams File writing and reading is accomplished with streams. There are input and output streams The term input means input to your program or consul from a file. The term output means from your program or consul to a file. Therefore: To read a file input stream is needed. To write to a file output stream is needed. The java.io package provides the classes for establishing input and output streams. 6

Hierarchy for Input Classes 7 Java classes to read files using streams

Selected Input Classes in the java.io Package 8 ClassDescription InputStream Abstract superclass representing a stream of raw bytes FileInputStream Input stream to read raw bytes of data from files ObjectInputStream Class to read/recover objects from a file written using ObjectOutputStream

FileInputStream Class FileInputStream Class reads the file byte by byte Different from scanner – scanner reads token by token Import java.io.*; try { //Reading a file (even text file) as a sequence of bytes FileInputStream fileInputStream = new FileInputStream(“input.txt"); byte[] arr = new byte[1024]; int actualBytesRead = fileInputStream.read(arr, 0, arr.length); }catch(IOException e){ e.printStackTrace(); } Use the read() method to read a fixed number of bytes

BufferedReader Class FileInputStream when used with other Stream classes can be very powerful Example: using BufferedReader Class with the FileInputStream class Read from character-input stream Converts the input produced by FileInputStream class to human readable form “Buffers” a sequence of characters

Reading using Streams (Example: Reading one character at a time) try{ FileInputStream file=new FileInputStream(“input.txt"); BufferedReader filereader=new BufferedReader(new InputStreamReader(file)); int index=0; int count=0; while(index>=0) { count++; //count the no. of characters in the file index=filereader.read(); } filereader.close(); file.close(); }// end of try; use a catch block with the IOException class 11 Use BufferefReader with the FileInputStream class Use the read() method to read one character at a time. Check out the API for other methods in this class.

Reading using Streams (Example: Reading one character at a time) try{ FileInputStream file=new FileInputStream(“input.txt"); BufferedReader filereader=new BufferedReader(new InputStreamReader(file)); int index=0; int count=0; while(index>=0) { count++; //count the no. of characters in the file index=filereader.read(); } filereader.close(); file.close(); }// end of try; use a catch block with the IOException class 12 Use BufferefReader with the FileInputStream class Use the read() method to read one character at a time. Check out the API for other methods in this class. To convert input stream to character stream

Example Reading Text File In this example a buffer stream was used. The buffer stream wraps the File Stream. The while loop and when we encounter -1, since this is the indicator that the end of a file has been reached (-1 is added to the end of the file when we create the file). Calling the read method of InputStreamReader class returns an int.If the end of the file is reached the value of the int is -1. The method reads one character at a time. In this example we are not saving what we read. The count counts the number of readings made in order to possibly create an array. We can repeat the loop once we have created an array and this time save the readings into the array by using a different format of the read method: int index=filereader.read(myarray, 0, count-1); this call places the readings into the array, where array is an array of char data types (from 0 th index to the last index). 13

Example Reading Text File The char array myarray, needs to be instantiated to the correct size before it is used in a while loop to capture the characters read. Therefore we need to loop twice through the file. The first time to capture the count of characters. We use the value of count to set the size of the char array. Close the stream objects used!!! The second time we create a new set of stream objects and we loop again through the file, this time using the read method that takes the char array as argument. Keep in mind that an array of char types (myarray) can be converted to a String by using: String str=new String(myarray); 14

Opening and Closing an Input Stream When we construct an input stream or output stream object, the JVM associates the file name, standard input stream, or standard output stream with our object. This is opening the file. When we are finished with a file, we optionally call the close method to release the resources associated with the file. Return valueMethod name and argument list voidclose( ) releases resources associated with an open input stream. Throws an IOException.

Reading Structured Text Files Some text files are organized into lines that represent a record -- a set of data values containing information about an item. The data values are separated by one or more delimiters; that is, a special character or characters that separate one value from the next. As we read the file, we need to parse each line; that is, separate the line into the individual data values called tokens. 16

Reading Structured Text Files (Example: Airline records) An airline company could store data in a file where each line represents a flight segment containing the following data: flight number origin airport destination airport number of passengers average ticket price These are called headers or field names of the record. Such a file could contain the following data : AA123,BWI,SFO,235,239.5 AA200,BOS,JFK,150,89.3 … In this case, the delimiter is a comma. This example shows two records (or two rows of data). 17

Remember the StringTokenizer Class/Split method in String class? The StringTokenizer class is designed to parse Strings into tokens. StringTokenizer is in the java.util package. When we construct a StringTokenizer object, we specify the delimiters that separate the data we want to tokenize. Can we use the scanner class to achieve this? Check out the constructors of the scanner class. We used scanner to read from a file. Can it “read” a string? 18

Reading Structured Text Files (Example: Airline records) try{ Scanner file = new Scanner( new File( "flights.txt" ) ); while ( file.hasNext( ) ) // test for the end of the file { String stringRead = file.nextLine( ); // read a line Scanner parse = new Scanner( stringRead ); // process the line read parse.useDelimiter( "," ); String flightNumber = parse.next( ); String origin = parse.next( ); String destination = parse.next( ); //code to process these tokens (origin, destination, etc) } }//use a catch black Use another scanner object to read and parse each line

In class Exercise Can you read structure files using the BufferedReader class? Try it with the airline example Do the following: Create a text file called “input.txt” with data with the following structure AA123,BWI,SFO,235,239.5 AA200,BOS,JFK,150,89.3 …. Write a client class that uses the BufferedReader class to reads the file line by line The client will print out the following output.

In class Exercise Sample output: Record No: 0 Flight: AA123 Origin: BWI Dest: SFO No of passesngers: 235 Ticket Price: Record No: 1 Flight: AA200 Origin: BOS Dest: JFK No of passesngers: 150 Ticket Price: 89.3

Writing to Text Files Several situations can exist: the file does not exist the file exists and we want to replace the current contents the file exists and we want to append to the current contents We specify whether we want to replace the contents or append to the current contents. 22

Selected java.io Output Classes 23 ClassDescription Writer Abstract superclass for output classes OutputStreamWriter Class to write output data streams OutputStream Abstract superclass representing an output stream of raw bytes FileWriter Class for writing to character files BufferedWriter More efficient writing to character files PrintWriter Prints basic data types, Strings, and objects PrintStream Supports printing various data types conveniently FileOutputStream Output stream for writing raw bytes of data to files ObjectOutputStream Class to write objects to a file

Hierarchy for Output Classes 24

Constructors for Writing to Text Files 25 ClassConstructor FileWriterFileWriter( String filename, boolean mode ) constructs a FileWriter object from a String representing the name of a file. If the file does not exist, it is created. If mode is false, the current contents of the file, if any, will be replaced. If mode is true, writing will append data to the end of the file. Throws an IOException. BufferedWriterBufferedWriter( Writer w ) constructs a BufferedWriter object from a Writer object

Buffering Writing data to the disk is much slower than writing data into main memory. When a class uses buffering, instead of writing one character at a time to the file, it accumulates the data in a temporary location in memory, called a buffer. When the buffer is full or is flushed, the accumulated data is written to the file in one efficient operation. 26

Methods of the BufferedWriter Class See Example 11.9 WriteTextFile.java and Example AppendTextFile.java 27 Return valueMethod name and argument list voidwrite( String s ) writes a String to the current OutputStream object. This method is inherited from the Writer class. Throws an IOException. voidnewLine( ) writes a line separator. Throws an IOException. voidclose( ) releases resources allocated to the BufferedWriter object. Throws an IOException.

Using BufferedWriter to Write to Files try { FileWriter fw = new FileWriter ( "grades.txt", false ); BufferedWriter bw = new BufferedWriter( fw ); String s="CS130: "; bw.write( s, 0, s.length()); counter=counter+s.length(); s="95"; bw.write( s, 0, s.length()); counter=counter+s.length(); bw.newLine(); s="Letter grade: "; bw.write( s, 0, s.length()); counter=counter+s.length(); s="A"; bw.write( s, 0, s.length()); counter=counter+s.length(); bw.newLine(); bw.flush(); bw.close( ); } catch (IOException e) { System.out.println( "Text errors" ); }

Writing Primitive Types to Text Files FileOutputStream, a subclass of the OutputStream class, is designed to write a stream of bytes to a file. The PrintWriter class is designed for converting primitive data types to characters and writing them to an output stream. print method, writes data without a newline println method, writes data then adds a newline 29

Writing to Structured Text Files 30 ClassConstructor FileOutputStreamFileOutputStream( String filename, boolean mode ) constructs a FileOutputStream object from a String representing the name of a file. If the file does not exist, it is created. If mode is false, the current contents of the file, if any, will be replaced. If mode is true, writing will append data to the end of the file. Throws a FileNotFoundException. PrintWriterPrintWriter( OutputStream os ) constructs a PrintWriter object from an OutputStream object

Useful PrintWriter Methods The argument can be any primitive data type (except byte or short), a char array, or an object. See Example 11.9 WriteGradeFile.java 31 Return valueMethod name and argument list voidprint( dataType argument ) writes a String representation of the argument to an output stream voidprintln( dataType argument ) writes a String representation of the argument to an output stream followed by a newline. voidclose( ) releases the resources associated with the PrintWriter object

public static void main( String [ ] args ) { try { FileOutputStream fos = new FileOutputStream ( "grades.txt", false ); // false means we will be writing to grades.txt, // rather than appending to it PrintWriter pw = new PrintWriter( fos ); // write data to the file pw.print( "CS130: " ); pw.println( 95 ); pw.print( "Letter grade: " ); pw.println( 'A' ); pw.print( "Current GPA: " ); pw.println( 3.68 ); pw.print( "Successful student as of Spring semester: " ); pw.println( true ); // release the resources associated with grades.txt pw.close( ); } catch ( FileNotFoundException fnfe ) { System.out.println( "Unable to find grades.txt" ); } Writing Primitive Types to Text Files

public static void main( String [ ] args ) { try { FileOutputStream fos = new FileOutputStream ( "grades.txt", false ); // false means we will be writing to grades.txt, // rather than appending to it PrintWriter pw = new PrintWriter( fos ); // write data to the file pw.print( "CS130: " ); pw.println( 95 ); pw.print( "Letter grade: " ); pw.println( 'A' ); pw.print( "Current GPA: " ); pw.println( 3.68 ); pw.print( "Successful student as of Spring semester: " ); pw.println( true ); // release the resources associated with grades.txt pw.close( ); } catch ( FileNotFoundException fnfe ) { System.out.println( "Unable to find grades.txt" ); } Writing Primitive Types to Text Files Use a FileOutputStream object 2 nd parameter is “false” which deletes the existing content of the file

public static void main( String [ ] args ) { try { FileOutputStream fos = new FileOutputStream ( "grades.txt", false ); // false means we will be writing to grades.txt, // rather than appending to it PrintWriter pw = new PrintWriter( fos ); // write data to the file pw.print( "CS130: " ); pw.println( 95 ); pw.print( "Letter grade: " ); pw.println( 'A' ); pw.print( "Current GPA: " ); pw.println( 3.68 ); pw.print( "Successful student as of Spring semester: " ); pw.println( true ); // release the resources associated with grades.txt pw.close( ); } catch ( FileNotFoundException fnfe ) { System.out.println( "Unable to find grades.txt" ); } Writing Primitive Types to Text Files Use a PrintWriter object with a FileOutputStream object to write into a text file

public static void main( String [ ] args ) { try { FileOutputStream fos = new FileOutputStream ( "grades.txt", false ); // false means we will be writing to grades.txt, // rather than appending to it PrintWriter pw = new PrintWriter( fos ); // write data to the file pw.print( "CS130: " ); pw.println( 95 ); pw.print( "Letter grade: " ); pw.println( 'A' ); pw.print( "Current GPA: " ); pw.println( 3.68 ); pw.print( "Successful student as of Spring semester: " ); pw.println( true ); // release the resources associated with grades.txt pw.close( ); } catch ( FileNotFoundException fnfe ) { System.out.println( "Unable to find grades.txt" ); } Writing Primitive Types to Text Files print(), println() method to write data

public static void main( String [ ] args ) { try { FileOutputStream fos = new FileOutputStream ( "grades.txt", false ); // false means we will be writing to grades.txt, // rather than appending to it PrintWriter pw = new PrintWriter( fos ); // write data to the file pw.print( "CS130: " ); pw.println( 95 ); pw.print( "Letter grade: " ); pw.println( 'A' ); pw.print( "Current GPA: " ); pw.println( 3.68 ); pw.print( "Successful student as of Spring semester: " ); pw.println( true ); // release the resources associated with grades.txt pw.close( ); } catch ( FileNotFoundException fnfe ) { System.out.println( "Unable to find grades.txt" ); } Writing Primitive Types to Text Files Close the PrintWriter object

public static void main( String [ ] args ) { try { FileOutputStream fos = new FileOutputStream ( "grades.txt", true ); // false means we will be writing to grades.txt, // rather than appending to it PrintWriter pw = new PrintWriter( fos ); // write data to the file pw.print( "CS130: " ); pw.println( 95 ); pw.print( "Letter grade: " ); pw.println( 'A' ); pw.print( "Current GPA: " ); pw.println( 3.68 ); pw.print( "Successful student as of Spring semester: " ); pw.println( true ); // release the resources associated with grades.txt pw.close( ); } catch ( FileNotFoundException fnfe ) { System.out.println( "Unable to find grades.txt" ); } Appending to Text Files 2 nd parameter is “true” which add the new data to the end of the file

BufferedWriter Vs PrintWriter BufferedWriter is more efficient Buffering helps to make the write process faster PrintWriter has a large number of methods to handle different data types Tedious to write using BufferedWriter You can combine them.

Using PrintWriter + BufferedWriter try { FileWriter fw = new FileWriter ( "grades.txt", false ); BufferedWriter bw = new BufferedWriter( fw ); PrintWriter pw=new PrintWriter(bw); pw.print( "CS130: " ); pw.println( 95 ); pw.print( "Letter grade: " ); pw.println( 'A' ); pw.print( "Current GPA: " ); pw.println( 3.68 ); pw.print( "Successful student as of Spring semester: " ); pw.println( true ); bw.flush(); pw.close( ); } catch (IOException e) { System.out.println( "Text errors" ); }

Opening and Closing Standard Streams Some streams are standard and the are available to any java program. The standard input stream (System.in), the standard output stream (System.out), and the standard error stream (System.err) are open when the program begins. They are intended to stay open and should not be closed. 40

Calling the close method is optional. When the program finishes executing, all the resources of any unclosed files are released. It is good practice to call the close method, however, especially if you will be opening a number of files (or opening the same file multiple times.) Do not close the standard input, output, or error devices, however. They are intended to remain open. 41 SOFTWARE ENGINEERING TIP

Closing an output stream When closing a Buffered output stream in addition to the close() method for the stream the method flush() should also be invoked: Flushing the output stream forces any buffered output bytes to be written out. 42