workshop for programming and systems management teachers

27
Workshop for Programming And Systems Management Teachers Chapter 11 Input / Output and Exceptions

Upload: anja

Post on 12-Jan-2016

28 views

Category:

Documents


0 download

DESCRIPTION

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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Workshop for Programming And Systems Management Teachers

Workshop for Programming And Systems Management Teachers

Chapter 11

Input / Output and Exceptions

Page 2: Workshop for Programming And Systems Management Teachers

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)

Page 3: Workshop for Programming And Systems Management Teachers

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

Page 4: Workshop for Programming And Systems Management Teachers

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

Sourceor

Destination

Program100110

ArrayString

File

Pipe

Byte DataCharacter Data

Page 5: Workshop for Programming And Systems Management Teachers

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)

Page 6: Workshop for Programming And Systems Management Teachers

Data Sink Classes

Sink Type Character Streams Byte Streams

File FileReaderFileWriter

FileInputStreamFileOutputStream

Memory CharArrayReaderCharArrayWriterStringReaderStringWriter

ByteArrayInputStreamByteArrayOutputStreamStringBufferInputStream

Pipe PipeReaderPipeWriter

PipeInputStreamPipeOutputStream

Page 7: Workshop for Programming And Systems Management Teachers

Processing Classes

Process Character Streams Byte Streams

Buffering BufferedReaderBufferedWriter

BufferedInputStreamBufferedOutputStream

Filtering FilterReaderFilterWriter

FilterInputStreamFilterOutputStream

ObjectSerialization

ObjectInputStreamObjectOutputStream

DataConversion

DataInputStreamDataOutputStream

Counting LineNumberReader LineNumberInputStream

PeekingAhead

PushbackReader PushbackInputStream

Printing PrintWriter PrintStream

Page 8: Workshop for Programming And Systems Management Teachers

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));

Page 9: Workshop for Programming And Systems Management Teachers

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

Page 10: Workshop for Programming And Systems Management Teachers

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?

Page 11: Workshop for Programming And Systems Management Teachers

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");

Page 12: Workshop for Programming And Systems Management Teachers

Try and Catch

• Use a try & catch clause to catch an exceptiontry {

code that can cause exceptions

} catch (ExceptionClassName varName) {

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

Page 13: Workshop for Programming And Systems Management Teachers

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 errortry {

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

}

Page 14: Workshop for Programming And Systems Management Teachers

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.

Page 15: Workshop for Programming And Systems Management Teachers

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 resourcestry {

code that can cause the exception} catch (FileNotFoundException ex) {

code to handle when the file isn’t found} finally {

code to always be executed}

Page 16: Workshop for Programming And Systems Management Teachers

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

Page 17: Workshop for Programming And Systems Management Teachers

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

Page 18: Workshop for Programming And Systems Management Teachers

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 }

Page 19: Workshop for Programming And Systems Management Teachers

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

Page 20: Workshop for Programming And Systems Management Teachers

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 datawriter.write(data);

– Close the buffered writer• writer.close();

Page 21: Workshop for Programming And Systems Management Teachers

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); }

Page 22: Workshop for Programming And Systems Management Teachers

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

Page 23: Workshop for Programming And Systems Management Teachers

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

Page 24: Workshop for Programming And Systems Management Teachers

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

Page 25: Workshop for Programming And Systems Management Teachers

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

Page 26: Workshop for Programming And Systems Management Teachers

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

Page 27: Workshop for Programming And Systems Management Teachers

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