Workshop for Programming And Systems Management Teachers

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

Exceptions. Definition Exception: something unexpected that can occur in the execution of a program e.g., divide by zero or attempt to open a file that.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
III. Streams. Introduction Often a program needs to bring in information from an external source or to send out information to an external destination.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
Lecture 7 File I/O (and a little bit about exceptions)‏
Files and Streams CS 21a Chapter 11 of Horstmann.
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.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives ->
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Java I/O Input: information brought to program from an external source
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.
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
Georgia Institute of Technology Speed part 3 Barb Ericson Georgia Institute of Technology May 2006.
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.
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.
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,
OOP with Java, David J. Barnes Input-Output1 A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated.
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.
Object Persistence and Object serialization CSNB534 Asma Shakil.
By Rachel Thompson and Michael Deck.  Java.io- a package for input and output  File I/O  Reads data into and out of the console  Writes and reads.
Files and Streams CS /02/05 L7: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
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.
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.
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.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
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.
1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
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.
OO Design and Programming II I/O: Reading and Writing
Chapter 10 – Exception Handling
Tirgul 13 Exceptions 1.
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Java Exceptions and I/O
Introduction to OO Program Design
CS102 – Exceptions David Davenport Latest: May 2015
I/O Basics.
Creating and Modifying Text part 2
Exceptions 10-Nov-18.
Java Programming Course
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.
CHAPTER 5 (PART 2) JAVA FILE INPUT/OUTPUT
CSS 161: Fundamentals of Computing
Unit 6 Working with files. Unit 6 Working with files.
Exception Handling.
Web Design & Development Lecture 7
Workshop for Programming And Systems Management Teachers
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Files and Streams in Java
Web Design & Development Lecture 8
I/O Exceptions & Working with Files
Exceptions 10-May-19.
Java Basics Exception Handling.
Exception Handling.
David Davenport Spring 2005
Presentation transcript:

Workshop for Programming And Systems Management Teachers Chapter 11 Input / Output and Exceptions Georgia Institute of Technology

Georgia Institute of Technology Learning Goals Understand at a conceptual and practical level Standard input and output Streams How to handle exceptions How to read from a character file How to write to a character file How to read and write objects (serialization) Georgia Institute of Technology

Standard Input and Output We have been using System.out.println to print output to a PrintStream (standard output). System.out.println(“First Name: “ + firstName); There is also a System.err PrintStream that can be used to write to the standard error output. System.err.println(“Error: no file name given”); You can use System.in to read a byte or bytes from an InputStream (standard input). int numGrades = System.in.read(); PrintStreams and InputStreams are in the java.io package. Georgia Institute of Technology

Input and Output Streams - java.io Java handles input and output through sequential streams of bits Programs can read from a stream or write to a stream Source or Destination Program 100110 Byte Data Character Data File The source or destination of the stream may be a file, a network socket, a string, an array of bytes, etc. The bit stream can be made up of objects, binary data, character data, images, sounds, etc. There is a tutorial on input and output streams at http://java.sun.com/docs/books/tutorial/essential/io/index.html. String Array Pipe Georgia Institute of Technology

Character versus Byte Streams Java input and output classes are categorized by the type of data they handle Character use Reader/Writer classes Byte use Stream classes Java input and output classes can also be categorized by data sink classes (read and write data from different sources like files, pipes, memory) processing classes (process the data, filter it, buffer it, print it) Georgia Institute of Technology

Georgia Institute of Technology Data Sink Classes You can read from files, memory in the form of character arrays, strings, or byte arrays, and from pipes. Pipes are ways that two threads can communicate. Georgia Institute of Technology

Georgia Institute of Technology Processing Classes The buffering process makes input and output more efficient since memory access is much faster than secondary storage (disk) access. You can extend the Filter classes to do your own special filtering of the data. Object serialization is a way of “freeze-drying” an object to pass it in a stream and reconstitute it on the other side back into an object. DataInputStream and DataOutputStream allow you to read and write java types in a machine independent way. The LineNumber classes keep track of the number of lines read from a file. The Pushback classes let you peek ahead at the next character or byte and yet still read it normally. The Print classes make it easy to print data. Georgia Institute of Technology

Chaining Input and Output Classes Often input or output classes are chained Passing one type of input/output class to the constructor for another One common thing is to chain a processing class with a data sink class Like a BufferedReader or BufferedWriter and a FileReader or FileWriter new BufferedReader(new FileReader(fileName)); Georgia Institute of Technology

Georgia Institute of Technology Exceptions Exceptions are disruptions in the normal flow of a program. Exception is short for exceptional event. The programmer is required to handle checked exceptions in Java like trying to read from a file that doesn’t exist Run-time exceptions do not have to be handled by the programmer like trying to invoke a method on a object reference that is null Children of RuntimeException Exceptions are unusual conditions that a program might want to handle. The compiler will give you an error message if you fail to catch a checked exception. Run-time exceptions are problems that are detected at run-time like divide by zero or null pointer exception. Runtime exceptions can occur anywhere in a program and in a typical program can be very numerous. Java does not require the programmer to handle them since to do so would require too much additional effort. Georgia Institute of Technology

Georgia Institute of Technology Exception Exercise Find the documentation for the Exception class What package is it in? What is the parent class? Find the documentation for the RuntimeException class What subclasses does it have? Find the documentation for the FileNotFoundException Does this exception need to be caught? Find the documentation for NullPointerException Georgia Institute of Technology

Causing Exceptions Exercise Try the following in DrJava interaction’s pane > String temp = null; > temp.toLowerCase() > int[] numberArray = {9, 8, 3}; > numberArray[5] > FileReader reader = new FileReader("test.txt"); > FileWriter writer = new FileWriter("test.txt"); Georgia Institute of Technology

Georgia Institute of Technology Try and Catch Use a try & catch clause to catch an exception try { code that can cause exceptions } catch (ExceptionClassName varName) { code to handle the exception } You can catch several exceptions Make the most general one last All exceptions are children of the class Exception There can be multiple catch clauses that each catch a different exception. If you do this be sure to catch the most general class last. Georgia Institute of Technology

Georgia Institute of Technology Try and Catch Example What if you want to know if a file isn’t found That you are trying to read from If this occurs you might want to use a JFileChooser to let the user pick the file You also want to handle any other error try { code that can cause the exception } catch (FileNotFoundException ex) { code to handle when the file isn’t found } catch (Exception ex) { code to handle the exception } Georgia Institute of Technology

Georgia Institute of Technology Catching Exceptions A catch clause will catch the given Exception class and any subclasses of it. So to catch all exceptions use: try { code that can throw the exception } catch (Exception e) { System.err.println(“Exception: “ + e.getMessage()); System.err.println(“Stack Trace is:”); e.printStackTrace(); } You can create your own exceptions by subclassing Exception or a child of Exception. You shouldn’t subclass RuntimeException. Georgia Institute of Technology

The optional finally clause A try and catch statement can have a finally clause Which will always be executed Will happened if no exceptions Will happened even if exceptions occur Used for releasing resources try { code that can cause the exception } catch (FileNotFoundException ex) { code to handle when the file isn’t found } finally { code to always be executed } Georgia Institute of Technology

Georgia Institute of Technology Throwing an Exception Use a throw clause to throw an exception /** Method that throws an exception */ public retValue methodName() throws ExceptionClassName { ... if (errorCondition) throw new ExceptionClassName(); } The method must report all exceptions that it throws Georgia Institute of Technology

Reading Lines of Character Data Enclose the code in a try and catch clause Catch FileNotFoundException if the file doesn’t exist And you want to give the user a chance to specify a new file using a JFileChooser Catch Exception to handle all other errors Create a buffered reader from a file reader for more efficient reading File names are relative to the current directory Loop reading lines from the buffered reader until the line is null Do something with the data Close the buffered reader Georgia Institute of Technology

Reading from File Example BufferedReader reader = null; String line = null; // try to read the file try { // create the buffered reader reader = new BufferedReader(new FileReader(fileName)); // loop reading lines till the line is null (end of file) while ((line = reader.readLine()) != null) { // do something with the line } // close the buffered reader reader.close(); } catch (Exception ex) { // handle exception Georgia Institute of Technology

Read From File Exercise Modify FortuneTellerPanel.java to add a constructor that takes a file name and reads the items for the array of fortunes from that file The first item in the file is the number of fortunes To use to create the array If there is any error tell the user and use the original array of fortunes Georgia Institute of Technology

Georgia Institute of Technology Writing to a File Use a try-catch clause to catch exceptions Create a buffered writer from a file writer writer = new BufferedWriter(new FileWriter(fileName)); Write the data writer.write(data); Close the buffered writer writer.close(); Georgia Institute of Technology

Writing to a File Example BufferedWriter writer = null; PictureInfo info = null; String endOfLine = System.getProperty("line.separator"); // Try to write the picture information try { // create a writer writer = new BufferedWriter(new FileWriter(directoryName + infoFileName)); // write out the number of picture information objects writer.write(pictureInfoArray.length + endOfLine); // loop writing the picture info to the file for (int i = 0; i < pictureInfoArray.length; i++) { info = pictureInfoArray[i]; writer.write(info.getFileName() + "|" + info.getCaption() + "|" + endOfLine); } // close the writer writer.close(); } catch (Exception ex) { System.out.println("Trouble writing the picture information to " + infoFileName); See the code in PhotoAlbum.java. Georgia Institute of Technology

Saving and Restoring Objects Applications often need to save the current objects to a file. So they aren’t lost when the application is stopped Applications often read objects from files. In the main method you call a method to read in the objects from a file Java provides classes to read objects and write objects ObjectInputStream, ObjectOutputStream The input and output classes are in the package java.io. To use the input and output classes import the java.io package import java.io.*; File input and output streams are specialized classes that handle reading and writing files. Piped input and output streams are specialized classes that handle reading and writing pipes. Pipes are used in network connections. Object input and output streams are specialized classes that handle reading and writing objects. Georgia Institute of Technology

Georgia Institute of Technology Object Output Import the package java.io import java.io.*; Make the object serializable public class Name implements Serializable Open the file for output using a FileOutputStream FileOutputStream fOut = new FileOutputStream(“fileName”); Create an ObjectOutputStream using the FileOutputStream as a parameter to the constructor. ObjectOutputStream oOut = new ObjectOutputStream(fOut); Output the object oOut.writeObject(theObject); Flush to make sure all objects are written oOut.flush(); The Serializable interface allows us to “freeze-dry” objects in a form that they can be reconstituted from later. Georgia Institute of Technology

Write Objects Exercise Modify WriteObjects/Person.java Create a class method that takes an array of Person objects and writes them to a file with the passed name Modify the main method to create an array of Person objects and call the method to write them to a file Make objects for yourself and your family Georgia Institute of Technology

Georgia Institute of Technology Object Input To input an object we need to Import the package java.io import java.io.*; Make the object serializable public class Name implements Serializable Open the file for input using a FileInputStream FileInputStream fIn = new FileInputStream(“fileName”); Create an ObjectInputStream using the FileInputStream as a parameter to the constructor. ObjectInputStream oIn = new ObjectInputStream(fIn); Input the object - must cast to class objectName = (ClassName) oIn.readObject(); Georgia Institute of Technology

Georgia Institute of Technology Read Objects Exercise Edit ReadObjects/Person.java Create a class method to read Person objects from a passed file name And return an array of Person objects Modify the main method to call this method And loop through the array of Person objects and use System.out.println(person) to print each Georgia Institute of Technology

Georgia Institute of Technology Summary There are many classes in java.io for handling input and output Use a buffer to make input or output more efficient Checked exceptions in java must be caught with a try and catch (optional finally) clause The code will not compile if the exception isn’t caught or thrown to the caller Runtime exceptions (children of RuntimeException) do not have to be in a try and catch clause Georgia Institute of Technology