Presentation is loading. Please wait.

Presentation is loading. Please wait.

Workshop for Programming And Systems Management Teachers

Similar presentations


Presentation on theme: "Workshop for Programming And Systems Management Teachers"— Presentation transcript:

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

2 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

3 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

4 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 String Array Pipe Georgia Institute of Technology

5 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

6 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

7 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

8 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

9 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

10 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

11 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

12 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

13 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

14 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

15 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

16 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

17 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

18 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

19 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

20 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

21 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

22 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

23 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

24 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

25 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

26 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

27 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


Download ppt "Workshop for Programming And Systems Management Teachers"

Similar presentations


Ads by Google