1 / 27

Workshop for Programming And Systems Management Teachers

Workshop for Programming And Systems Management Teachers. Chapter 11 Input / Output and Exceptions. 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

anja
Download Presentation

Workshop for Programming And Systems Management Teachers

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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(); 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 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. Data Sink Classes Georgia Institute of Technology

  7. Processing Classes 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. 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 Georgia Institute of Technology

  10. 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? • What is the parent class? • Find the documentation for the FileNotFoundException • What is the parent class? • Does this exception need to be caught? • Find the documentation for NullPointerException • What is the parent class? • Does this exception need to be caught? Georgia Institute of Technology

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

  12. Try and Catch • Use a try & catch clause to catch an exception try { code that can cause exceptions } catch (ExceptionClassNamevarName) { code to handle the exception } 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 Georgia Institute of Technology

  13. 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. 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. 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. Throwing an Exception • Use a throw clause to throw an exception /** Method that throws an exception */ public retValue methodName() throwsExceptionClassName { ... 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. 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); } 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 Georgia Institute of Technology

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

More Related