Files Chap. 10 Streams, Readers, Writers 1. 2 Problem In our array example, we entered the students' names and scores from the keyboard. In many situations.

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Advertisements

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.
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.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
File I/O Chapter 10 Chapter Contents Chapter Objectives 10.1 Introductory Example: Weather Data Analysis 10.2 Java/s I/O System: Readers, Writers, Streams.
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.
Chapter 9 Streams and File I/O Overview of Streams and File I/O
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
Using Processing Stream. Predefined Streams System.in InputStream used to read bytes from the keyboard System.out PrintStream used to write bytes to the.
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.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
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.
Chapter 8 Overview – Learn to use try catch blocks – Learn to use streams – Learn to use text files.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
1 Introduction to Console Input  Primitive Type Wrapper Classes  Converting Strings to Numbers  System.in Stream  Wrapping System.in in a Buffered.
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.
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.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Java I/O Input: information brought to program from an external source
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.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
Two Ways to Store Data in a File Text format Binary format.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
1 Java Console I/O Introduction. 2 Java I/O You may have noticed that all the I/O that we have done has been output The reasons –Java I/O is based on.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
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.
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 9 l Streams and Simple File I/O l Exception Handling with File.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
File IO Basics By Dan Fleck Coming up: Data Streams.
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.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
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.
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.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
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.
© 2004 Pearson Addison-Wesley. All rights reserved December 5, 2007 I/O Exceptions & Working with Files ComS 207: Programming I (in Java) Iowa State University,
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.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Keerthi Nelaturu Url: site.uottawa.ca/~knela006
Lecture 8: I/O Streams types of I/O streams Chaining Streams
IO in java.
OO Design and Programming II I/O: Reading and Writing
Streams & File Input/Output (I/O)
I/O Basics.
I/O Streams- Basics Byte Streams and Character Streams
Streams and File I/O Chapter 14.
Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on the purpose of exceptions exception messages the.
CSS 161: Fundamentals of Computing
Computer Programming with JAVA
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Exception Handling Contents
David Davenport Spring 2005
Presentation transcript:

Files Chap. 10 Streams, Readers, Writers 1

2 Problem In our array example, we entered the students' names and scores from the keyboard. In many situations this is not practical because there is too much data. What we would like is to be able to read this data directly from a file: Executing Program Joe Blow 80 L. Nyhoff Mary Smith 95

3 Output streams move bytes of data from the program to an output device.Output streams move bytes of data from the program to an output device. Java's I/O System Executing Program Output Stream Input Stream Input streams provide ways to move bytes of data from an input device to a program.Input streams provide ways to move bytes of data from an input device to a program. All input and output in Java is accomplished by classes called streams.All input and output in Java is accomplished by classes called streams.

4 Predefined Streams System class provides three public class variables that are streams: System.in – –InputStream object, usually associated with the keyboard System.out – –a buffered PrintStream object, usually associated with the screen or an active window System.err – –an unbuffered PrintStream object usually associated with the screen or console window

5 Wrapper Classes The PrintStream class provides convenient print() and println() methods for outputting primitive type values. Basically, all the Screen class in ann.easyio does is send these messages to System.out ; e.g., System.out.println("The square root of " + value + " = " + Math.sqrt(value) );

6 // From Screen.java in easy.io /** println(double) displays a double followed * by a newline. * Precondition: System.out is open; * value is a double. * Postcondition: value and a newline have * been appended to System.out. * Return: the receiver */ public Screen println(double value) { System.out.println(value); return this; }

7 However, the InputStream class provides only methods for reading bytes. –To read at a higher level we must "wrap" System.in with another class (a Reader class) that provides some higher-level methods (e.g., the BufferedReader class has read() and readLine() methods for reading characters and strings, respectively).

8 Example: BufferedReader class BufferedReader myReader = new (BufferedReader ( new InputStreamReader( System.in )); myReader InputStreamReader System.in BufferReader InputStream Now we can send myReader either –the.read() message for a single char value or –the.readLine() message for an entire line of text

9 A BufferedReader is so named because it buffers the input, which improves program performance. Input Buffer myReader InputStreamReader System.in BufferReader InputStream

10 But... these are the only input methods provided in class BufferedReader ! So if we need more powerful input methods — e.g., readInt(), readDouble() — we must build them ourselves using read() and readLine(). This is what the Keyboard class in ann.easyio does.

/** readDouble tries to read the next word as a double value. * Precondition: System.in is open and contains a double * value. * Postcondition: The read position has advanced beyond the * next word. * Return: the double equivalent of the next word. * NOTE: In earlier versions of Java that don't support * parseDouble(), replace the return statement by: * return Double.valueOf(myString).doubleValue(); */ public double readDouble() { myString = readWord(); return Double.parseDouble(myString); } private static BufferedReader myReader = new BufferedReader( new InputStreamReader( System.in)); 11

12 Readers and Writers Java’s current I/O system provides: – –Reader and Writer classes: provide support for char (16-bit Unicode) I/O. – –InputStream and OutputStream classes: provide support for byte I/O. General rule of thumb: Use a reader or writer class whenever possible. Revert to stream classes only when necessary. See the Java API

13 Exceptions And one more "complication"... Many things can go wrong when doing I/O: input file doesn't exist invalid input data output file is in use or doesn't exist... When such an error occurs, the method in which this abnormal event happened can throw an exception.

14 try { // call a method that may // throw an exception } catch (ExceptionType variable) { // Action to take when // an exception of this // type is thrown } Java can catch the exception if it happens in a try block: This is followed by one or more catch blocks that determine the kind of exception and specify how to handle it:

15 General form: try { // Call to exception-throwing method... } catch (ExceptionType 1 variable_name 1 ) { // Code to handle ExceptionType 1 exceptions } catch (ExceptionType 2 variable_name 2 ) { // Code to handle ExceptionType 2 exceptions } //... may be more catch blocks finally { // Optional finally block of // code to execute at the end }

16 If the method called in the try block: doesn't throw an exception, control returns to the try block and continues on to the end of it, bypasses all the catch blocks, and continues with the finally block, if there is one; throws an exception of type ExceptionType i throw new ExceptionType i (); control is transferred to the catch block for that type, executes the code in it, and continues on to the finally block, if there is one (unless the catch block terminates execution).

17 The Exception Hierarchy DataFormatException EOFException FileNotFoundException InterruptedIOException IOException... RuntimeException Exception... Note: A catch block for an exception of a certain type can be used for exceptions of any type derived from (descendant of) that type. In particular, a catch block for type Exception (the most general type at the top of this hierarchy) can catch an exception of any other type. See the Java API

18 Most of Java's I/O and file-handling methods throw exceptions. In particular, BufferedReader 's read() and readLine() methods throw an IOException if an I/O error occurs. Example:Redo the student-grades example from the arrays section, but without using the ann.easyio package. Note:Readers, writers, and exceptions must be imported from the java.io package. See the Java API This means that to use these methods, we must use the try-catch mechanism.

19 import java.io.*; // BufferedReader, Exception,... import ann.util.*; // Controller.fatal() class Assignment { public Assignment() { studentNames = null; studentScores = null; size = 0; } public double average() { int sum = 0; for (int i = 0; i < size; i++) sum += studentScores[i]; return (double)sum / size; } public void printStats() { double theAverage = average(); System.out.println("\nThe average is: " + average()); System.out.println("The deviations are:"); for (int i = 0; i < size; i++) System.out.println(studentNames[i] + " " + studentScores[i] + " [" + + (studentScores[i] - theAverage" + "]" ); }

20 public void read() { System.out.print("Enter the size of the class: "); BufferedReader aReader = new BufferedReader( new InputStreamReader( System.in )); String numberString; try { numberString = aReader.readLine(); size = Integer.parseInt(numberString); if (size <= 0) Controller.fatal( "Assignment.read()", "Negative array size: " + size ); else { studentNames = new String [size]; studentScores = new double [size]; } catch (IOException exc) { Controller.fatal( "Assignment.read()", e.toString() ); }

21 String name; System.out.println("Enter the names and scores of "+ "the students in the class: "); for (int i = 0; i < size; i++) { System.out.print((i + 1) + ": "); try { studentNames[i] = aReader.readLine(); numberString = aReader.readLine(); studentScores[i] = Double.parseDouble(numberString); } catch (IOException ioe) { Controller.fatal( "Assignment.read()", "Input error reading student info" ); } private int size; private String [] studentNames; private double [] studentScores; } // end of class Assignment

22 class Teacher1 { public static void main(String [] args) { Assignment theAssignment = new Assignment(); theAssignment.read(); theAssignment.printStats(); } Sample run: Enter the size of the class: 3 Enter the names and scores of the students in the class: 1: Joe Blow 80 2: L. Nyhoff 100 3: Mary Doe 90 The average is: 90.0 The deviations are: Joe Blow 80.0 [-10.0] L. Nyhoff [10.0] Mary Doe 90.0 [0.0]

23 Reading from a File We use a FileReader class to build a stream from a file to our program by sending the name of the file to its constructor: FileReader(input_filename) However, FileReader has no methods to read numbers or even String values from the file  its read() method only reads a single char value.

24 But... the BufferedReader class has: –a readLine() method that can read String values, and –a constructor we can use to wrap a BufferedReader around any Reader, in particular, around a FileReader.

25 So we build an input stream from the file to our program with: BufferedReader in = new BufferedReader( new FileReader(input_filename) ); J. Doe in BufferReader FileReader input.txt J. D o e Now, the BufferedReader in can be send a readLine() message: valueString = in.readLine();

26 How does one know when all the data in a file has been read?How does one know when all the data in a file has been read? –When no data is read, the readLine() method returns the value null; read() returns -1 valueString = inFile.readLine(): while (valueString != null) { … // process valueString valueString = inFile.readLine(); } Then close the reader: in.close();Then close the reader: in.close(); It's also possible to check for other things such as an empty line with no text:It's also possible to check for other things such as an empty line with no text: if (valueString.equals("")) continue; if (valueString.equals("")) continue; Go to Slide 27

27 Summary of how to Read from a File 1.Build a BufferedReader aReader by wrapping one around a FileReader : BufferedReader inFile = new BufferedReader( new FileReader( input_filename )); –This can throw a FileNotFound exception, so do this in a try block; this is a special kind of IOException so we can just catch an IOException (or an Exception ). –The name of the file can be:  "Hard-wired": Use "name_of_file"  Input into a String variable  Entered into arg[0] from the command line.

28 2.Use an input loop to read from aReader ; e.g., valueString = aReader.readLine(): while (valueString != null) { // process valueString valueString = aReader.readLine(); } –This can throw an IOException, so do this in a try block. –Convert valueString to numeric values if necessary. 3.Close aReader : aReader.close();

29 Writing to a File 1. Build a PrintWriter object connected to the output file. For this, we need three classes: Fil eWriter to construct an output stream to the file Wrap this in a BufferedWriter to improve output efficiency Wrap this in a PrintWriter, which provides print() and println() met hods.

30 PrintWriter aWriter = new PrintWriter( new BufferedWriter( new FileWriter( outFilename ))); An IOException can occur, so this must be done in a try block. 2. Use aWriter.print() and aWriter.println() to write output to the file. 3. Close the file: aWriter.close();

31 Example:Redo the student-grades example from the arrays section, but with file I/O. import java.io.*; // BufferedReader, FileReader,... import ann.util.*; // Controller class Assignment { public Assignment() { studentNames = null; studentScores = null; size = 0; } public double average() { int sum = 0; for (int i = 0; i < size; i++) sum += studentScores[i]; return (double)sum / size; }

public void printStats(String outFilename) { try { PrintWriter aWriter = new PrintWriter( new BufferedWriter( new FileWriter( outFilename ))); double theAverage = average(); aWriter.println("\nThe average is: " + average()); aWriter.println("The deviations are:"); for (int i = 0; i < size; i++) aWriter.println(studentNames[i] + " " + studentScores[i] + " [" + + (studentScores[i] - theAverage" + "]" ); aWriter.close(); } catch (IOException ioe) { Controller.fatal("Assignment.printStats()", ioe.toString()); } 32

public void read(String inFilename) { String numberString; try { BufferedReader aReader = new BufferedReader( new FileReader( inFilename) ); numberString = aReader.readLine(); size = Integer.parseInt(numberString); if (size <= 0) { aReader.close(); Controller.fatal("Assignment.read()", "Illegal array size: " + size); //-- or we could throw an exception } else { studentNames = new String [size]; studentScores = new double [size]; } 33 Can throw NumberFormatException

for (int i = 0; i < size; i++) { studentNames[i] = aReader.readLine(); numberString = aReader.readLine(); if (studentNames[i] == null || numberString == null) { aReader.close(); Controller.fatal("Assignment.read()", "Out of data for student " + i); //-- or we could throw an exception } studentScores[i] = Double.parseDouble(numberString); } aReader.close(); } catch (Exception e) { Controller.fatal("Assignment.read()", e.toString()); } private int size; private String [] studentNames; private double [] studentScores; } // end of class Assignment 34 Can throw NumberFormatException

class Teacher3 { public static void main(String [] args) { if (args.length < 2) Controller.fatal("main(): ", "Missing file name"); String inFilename = args[0], outFilename = args[1]; Assignment theAssignment = new Assignment(); theAssignment.read(inFilename); theAssignment.printStats(outFilename); } 35

% cat scores.out The average is: 90.0 The deviations are: Joe Blow 80.0 [-10.0] L. Nyhoff [10.0] Mary Q. Doe 90.0 [0.0] 36 % cat scores.txt 3 Joe Blow 80 L. Nyhoff 100 Mary Q. Doe 90 % java Teacher3 scores.txt scores.out

Suppose we throw the exceptions in Assignment 's read() as described in the comments: public void read(String inFilename) { String numberString; try { BufferedReader aReader = new BufferedReader( new FileReader(inFilename) ); numberString = aReader.readLine(); size = Integer.parseInt(numberString); } else { studentNames = new String [size]; studentScores = new double [size]; } 37 throws EOFException, IOException if (size <= 0) { throw new IOException( "IIlegal array size: " + size);

for (int i = 0; i < size; i++) { studentNames[i] = aReader.readLine(); numberString = aReader.readLine(); if (studentNames[i] == null || numberString == null) { } studentScores[i] = Double.parseDouble(numberString); } aReader.close(); } catch (IOException ioe) { Controller.fatal("Assignment.read()", ioe.toString()); } 38 throw new EOFException( "Out of data for student " + i);

And change main() to: public static void main(String [] args) { if (args.length < 2) Controller.fatal("main(): ", "Missing file name"); String inFilename = args[0], outFilename = args[1]; Assignment theAssignment = new Assignment(); try { theAssignment.read(inFilename); theAssignment.printStats(outFilename); } 39 catch (EOFException e) { System.out.println(e.toString()); } catch (IOException e) { System.out.println(e.toString()); } catch (Exception e) { System.out.println(e.toString()); } or just

% java Teacher4 scores1.txt out *** Assignment.read(): java.io.EOFException: Out of data for student 3 40 % java Teacher4 scores2.txt out *** Assignment.read(): java.io.IOException: Illegal array size: -1 % cat scores1.txt 4 Joe Blow 80 L. Nyhoff 100 Mary Q. Doe 90 % cat scores2.txt Joe Blow 80 L. Nyhoff 100 Mary Q. Doe 90

41 Binary Files Readers and Writers use text-based I/O in which each character is stored using 2 bytes; e.g, requires 20 bytes. Storing its 32-bit binary representation, would require only 4 bytes. Java's Stream classes can be used for such binary I/O. Two of these are DataInputStream and DataOutputStream. They contain methods — e.g., readDouble(), writeDouble() — for reading and writing binary data. (See Fig.10.3 for a demo.)

/** DataStreamDemo.java demonstrates DataOutputStreams and DataInpusStreams. * Ouptut (file) : a sequence of doubles to a file via a DataOutputStream * Input(file) : the doubles from this file via a DataInputStream * Output(screen): the sequence of doubles */ import ann.util.*; // Controller import java.io.*; // DataOutputStream, DataInputStream... class DataStreamDemo extends Object { public static void main(String [] args) { DataOutputStream dataOut = null; DataInputStream dataIn = null; try { dataOut = new DataOutputStream( new BufferedOutputStream( new FileOutputStream("numbers.dat"))); for (double val = 1; val <= 10000; val *= 10) dataOut.writeDouble(val); dataOut.close();

try { dataIn = new DataInputStream( new BufferedInputStream( new FileInputStream("numbers.dat") )); double value; for (;;) { value = dataIn.readDouble(); // EOFException breaks if no more data System.out.println(value); } catch (EOFException e) { dataIn.close(); System.out.println("Processing complete.\n"); } catch (Exception e) { Controller.fatal("main()", e.toString()); }

holmes ~/cs185/classprogs$ java DataStreamDemo Processing complete. holmes ~/cs185/classprogs$ cat numbers.dat ~/cs185/classprogs$