java programming week 9: input/ouput and exception handling, files and streams (chapter 11 and...
TRANSCRIPT
Java Programming
Week 9: Input/Ouput and Exception Handling,Files and Streams
(Chapter 11 and Chapter 19)
COIT11134 - Java Programming 2
• To be able to read and write text files
• To learn how to throw exceptions
• To be able to design your own exception classes
• To understand the difference between checked and unchecked exceptions
• To learn how to catch exceptions
• To know when and where to catch an exception
• To become familiar with the concepts of text and binary format
• To learn about encryption
Chapters Goals
COIT11134 - Java Programming 3
• Simplest way to read text: use Scanner class
• To read from a disk file, construct a FileReader
• Then, use the FileReader to construct a Scanner object FileReader reader = new FileReader("input.txt");
Scanner in = new Scanner(reader);
• Use the Scanner methods to read data from file next, nextLine, nextInt, and nextDouble
Reading Text Files
COIT11134 - Java Programming 4
• To write to a file, construct a PrintWriter object PrintWriter out = new PrintWriter("output.txt");
• If file already exists, it is emptied before the new data are written into it
• If file doesn't exist, an empty file is created
• Use print and println to write into a PrintWriter: out.println(29.95); out.println(new Rectangle(5, 10, 15, 25));out.println("Hello, World!");
• You must close a file when you are done processing it: out.close();
Otherwise, not all of the output may be written to the disk file
Writing Text Files
COIT11134 - Java Programming 5
• When the input or output file doesn't exist, a FileNotFoundException can occur
• To handle the exception, label the main method like this: public static void main(String[] args) throws FileNotFoundException
(Check FileReader, PrintWriter and Scanner constructors, they throws FileNotFoundException)
FileNotFoundException
COIT11134 - Java Programming 6
• Reads all lines of a file and sends them to the output file, preceded by line numbers
• Sample input file: Mary had a little lamb Whose fleece was white as snow. And everywhere that Mary went, The lamb was sure to go!
• Program produces the output file: /* 1 */ Mary had a little lamb /* 2 */ Whose fleece was white as snow. /* 3 */ And everywhere that Mary went, /* 4 */ The lamb was sure to go!
• Program can be used for numbering Java source files
A Sample Program
COIT11134 - Java Programming 7
01: import java.io.FileReader;02: import java.io.FileNotFoundException;03: import java.io.PrintWriter;04: import java.util.Scanner;05: 06: public class LineNumberer07: {08: public static void main(String[] args)09: throws FileNotFoundException10: {11: Scanner console = new Scanner(System.in);12: System.out.print("Input file: ");13: String inputFileName = console.next();14: System.out.print("Output file: ");15: String outputFileName = console.next();16: 17: FileReader reader = new FileReader(inputFileName);18: Scanner in = new Scanner(reader);19: PrintWriter out = new PrintWriter(outputFileName);20: int lineNumber = 1;
ch11/fileio/LineNumberer.java
Continued
COIT11134 - Java Programming 8
21: 22: while (in.hasNextLine())23: {24: String line = in.nextLine();25: out.println("/* " + lineNumber + " */ " + line);26: lineNumber++;27: }28: 29: out.close();30: }31: }
ch11/fileio/LineNumberer.java (cont.)
COIT11134 - Java Programming 9
What happens when you supply the same name for the input and output files to the LineNumberer program?
Self Check 11.1
Answer: When the PrintWriter object is created, the output file is emptied. Sadly, that is the same file as the input file. The input file is now empty and the while loop exits immediately.
COIT11134 - Java Programming 10
What happens when you supply the name of a nonexistent input file to the LineNumberer program?
Self Check 11.2
Answer: The program catches a FileNotFoundException, prints an error message, and terminates.
COIT11134 - Java Programming 11
Two steps:
• Reporting - indicate where the error occur
• Recovery - what to do if the error occurs
sometimes, they are far away from each other (e.g. method calls, different classes)
Exception Handling
COIT11134 - Java Programming 12
One easy way:• Throw an exception object to signal an exceptional
condition
• Example: IllegalArgumentException: illegal parameter value IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception;
• No need to store exception object in a variable: throw new IllegalArgumentException("Amount exceeds balance");
• When an exception is thrown, method terminates immediately
• Execution continues with an exception handler
Throwing Exceptions
COIT11134 - Java Programming 13
public class BankAccount { public void withdraw(double amount) { if (amount > balance) { IllegalArgumentException exception = new IllegalArgumentException("Amount
exceeds balance"); throw exception; } balance = balance - amount; } . . . }
Example
COIT11134 - Java Programming 14
throw exceptionObject;
Example:
throw new IllegalArgumentException();
Purpose:
To throw an exception and transfer control to a handler for this exception type.
Syntax 11.1 Throwing an Exception
COIT11134 - Java Programming 15
How should you modify the deposit method to ensure that the balance is never negative?
Self Check 11.3
Answer: Throw an exception if the amount being deposited is less than zero.
COIT11134 - Java Programming 16
Suppose you construct a new bank account object with a zero balance and then call withdraw(10). What is the value of balance afterwards?
Self Check 11.4
Answer: The balance is still zero because the last statement of the withdraw method was never executed.
COIT11134 - Java Programming 17
Hierarchy of Exception Classes
COIT11134 - Java Programming 18
• Two types of exceptions:
• Checked o The compiler checks that you don't ignore them
o Due to external circumstances that the programmer cannot prevent
o Majority occur when dealing with input and output
o For example, IOException
Checked and Unchecked Exceptions
COIT11134 - Java Programming 19
• Unchecked:
o Extend the class RuntimeException or Error
o They are the programmer's fault
o Examples of runtime exceptions: NumberFormatException IllegalArgumentException NullPointerException
o Example of error: OutOfMemoryError
Checked and Unchecked Exceptions
COIT11134 - Java Programming 20
• Categories aren't perfect: • Scanner’s nextInt throws unchecked InputMismatchException (i.e. compiler doesn’t pick up)
• Actually, programmer cannot prevent users from entering incorrect input
• “unchecked” makes the class easy to use for beginning programmers (in fact, checked would be better)
• Deal with checked exceptions principally when programming with files and streams
• For example, use a Scanner to read a file String filename = . . .; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader);
FileReader constructor can throw a FileNotFoundException
Checked and Unchecked Exceptions
COIT11134 - Java Programming 21
Two choices: 1. Handle the exception 2. Tell compiler that you want method to be terminated when the
exception occurs
• Use throws specifier so method can throw a checked
exception
public void read(String filename) throws FileNotFoundException { FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); . . . }
• For multiple exceptions: public void read(String filename) throws IOException, ClassNotFoundException
Checked and Unchecked Exceptions
Continued
COIT11134 - Java Programming 22
• Keep in mind inheritance hierarchy:
If method can throw an IOException and
FileNotFoundException, only use IOException
• Better to declare exception (throws) than to handle it incompetently
Checked and Unchecked Exceptions (cont.)
COIT11134 - Java Programming 23
accessSpecifier returnType methodName(parameterType parameterName, . . .) throws ExceptionClass, ExceptionClass, . . .
Example:public void read(BufferedReader in) throws IOException
Purpose:To indicate the checked exceptions that this method can throw.
Syntax 11.2 Exception Specification
COIT11134 - Java Programming 24
Suppose a method calls the FileReader constructor and the read method of the FileReader class, which can throw an IOException. Which throws specification should you use?
Self Check 11.5
Answer: The specification throws IOException is sufficient because FileNotFoundException is a subclass of IOException.
COIT11134 - Java Programming 25
Why is a NullPointerException not a checked exception?
Self Check 11.6
Answer: Because programmers should simply check for null pointers instead of trying to handle a NullPointerException.
COIT11134 - Java Programming 26
• Install an exception handler with try/catch statement
• try block contains statements that may cause an exception
• catch clause contains handler for an exception type
Catching Exceptions
Continued
COIT11134 - Java Programming 27
• Example: try { String filename = . . .; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader);
String input = in.next(); int value = Integer.parseInt(input); . . . } catch (IOException exception) { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println("Input was not a number"); }
Catching Exceptions (cont.)
COIT11134 - Java Programming 28
• Statements in try block are executed
• If no exceptions occur, catch clauses are skipped
• If exception of matching type occurs, execution jumps to catch clause
• If exception of another type occurs, it is thrown until it is caught by another try block
• catch (IOException exception) block • exception contains reference to the exception object that was
thrown • catch clause can analyze object to find out more details • exception.printStackTrace(): printout of chain of method
calls that lead to exception
Catching Exceptions
COIT11134 - Java Programming 29
try { statement statement . . . } catch (ExceptionClass exceptionObject) { statement statement . . . } catch (ExceptionClass exceptionObject) { statement statement . . . } . . .
Syntax 11.3 General Try Block
Continued
COIT11134 - Java Programming 30
Example:
try { System.out.println("How old are you?"); int age = in.nextInt(); System.out.println("Next year, you'll be " + (age + 1)); } catch (InputMismatchException exception) { exception.printStackTrace(); }
Syntax 11.3 General Try Block (cont.)
Continued
COIT11134 - Java Programming 31
Purpose:
To execute one or more statements that may generate exceptions. If an exception occurs and it matches one of the catch clauses, execute the first one that matches. If no exception occurs, or an exception is thrown that doesn't match any catch clause, then skip the catch clauses.
Syntax 11.3 General Try Block (cont.)
COIT11134 - Java Programming 32
Suppose the file with the given file name exists and has no contents. Trace the flow of execution in the try block in this section (slide 27).
Self Check 11.7
Answer: The FileReader constructor succeeds, and in is constructed. Then the call in.next() throws a NoSuchElementException, and the try block is aborted. None of the catch clauses match, so none are executed. If none of the enclosing method calls catch the exception, the program terminates.
COIT11134 - Java Programming 33
Is there a difference between catching checked and unchecked exceptions?
Self Check 11.8
Answer: No – you catch both exception types in the same way, as you can see from the code example on page 508-509. Recall that IOException is a checked exception and NumberFormatException is an unchecked exception.
COIT11134 - Java Programming 34
• Exception terminates current method
• Danger: Can skip over essential code
• Example: reader = new FileReader(filename); Scanner in = new Scanner(reader); readData(in); reader.close(); // May never get here
• Must execute reader.close() even if exception happens
• Use finally clause for code that must be executed "no matter what"
The finally Clause
COIT11134 - Java Programming 35
FileReader reader = new FileReader(filename); try { Scanner in = new Scanner(reader); readData(in); } finally { reader.close(); // if an exception occurs, finally clause is also executed // before exception is passed to its handler
}
The finally Clause
COIT11134 - Java Programming 36
• Executed when try block is exited in any of three ways: • After last statement of try block • After last statement of catch clause, if this try block caught an
exception • When an exception was thrown in try block and not caught
• Recommendation: don't mix catch and finally clauses in same try block
The finally Clause
COIT11134 - Java Programming 37
try { statement statement . . . } finally { statement statement . . . }
Syntax 11.4 The finally Clause
Continued
COIT11134 - Java Programming 38
Example:
FileReader reader = new FileReader(filename); try { readData(reader); } finally { reader.close(); }
Purpose:
To ensure that the statements in the finally clause are executed whether or not the statements in the try block throw an exception.
Syntax 11.4 The finally Clause (cont.)
Example:use catch and finally in this way
try { PrintWriter out = new PrintWriter(filename);
try { // write output } finally { out.close(); } }
catch (IOException exception) { // handle exception }
COIT11134 - Java Programming 39
COIT11134 - Java Programming 40
Why was the out variable declared outside the try block?
Self Check 11.9
Answer: If it had been declared inside the try block, its scope would only have extended to the end of the try block, and the catch clause could not have closed it.
COIT11134 - Java Programming 41
• You can design your own exception types – subclasses of Exception or RuntimeException
if (amount > balance) { throw new InsufficientFundsException( "withdrawal of " + amount + " exceeds balance of “ + balance); }
• Make it an unchecked exception – programmer could have avoided it by calling getBalance first
Designing Your Own Exception Types
COIT11134 - Java Programming 42
• Extend RuntimeException or one of its subclasses
• Supply two constructors 1. Default constructor 2. A constructor that accepts a message string describing reason
for exception
Designing Your Own Exception Types
COIT11134 - Java Programming 43
public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() {}
public InsufficientFundsException(String message) { super(message); } }
Designing Your Own Exception Types
COIT11134 - Java Programming 44
What is the purpose of the call super(message) in the second InsufficientFundsException constructor?
Self Check 11.11
Answer: To pass the exception message string to the RuntimeException superclass.
COIT11134 - Java Programming 45
Suppose you read bank account data from a file. Contrary to your expectation, the next input value is not of type double. You decide to implement a BadDataException. Which exception class should you extend?
Self Check 11.12
Answer: Exception or IOException are both good choices. Because file corruption is beyond the control of the programmer, this should be a checked exception, so it would be wrong to extend RuntimeException.
COIT11134 - Java Programming 46
• Program • Asks user for name of file • File expected to contain data values • First line of file contains total number of values • Remaining lines contain the data • Typical input file:
3 1.45 -2.1 0.05
A Complete Example
COIT11134 - Java Programming 47
• What can go wrong? • File might not exist • File might have data in wrong format
• Who can detect the faults? • FileReader constructor will throw an exception when file does not
exist • Methods that process input need to throw exception if they find error
in data format
• What exceptions can be thrown?• FileNotFoundException can be thrown by FileReader
constructor• IOException can be thrown by close method of FileReader• BadDataException, a custom checked exception class
A Complete Example
Continued
COIT11134 - Java Programming 48
• Who can remedy the faults that the exceptions report?
• Only the main method of DataAnalyzer program interacts with
user • Catches exceptions • Prints appropriate error messages • Gives user another chance to enter a correct file
A Complete Example (cont.)
COIT11134 - Java Programming 49
01: import java.io.FileNotFoundException;02: import java.io.IOException;03: import java.util.Scanner;04: 05: /**06: This program reads a file containing numbers and analyzes its contents.07: If the file doesn't exist or contains strings that are not numbers, an08: error message is displayed.09: */10: public class DataAnalyzer11: {12: public static void main(String[] args)13: {14: Scanner in = new Scanner(System.in);15: DataSetReader reader = new DataSetReader();16: 17: boolean done = false;18: while (!done) 19: {20: try 21: {22: System.out.println("Please enter the file name: ");23: String filename = in.next();
ch11/data/DataAnalyzer.java
Continued
COIT11134 - Java Programming 50
24: 25: double[] data = reader.readFile(filename);26: double sum = 0;27: for (double d : data) sum = sum + d; 28: System.out.println("The sum is " + sum);29: done = true;30: }31: catch (FileNotFoundException exception)32: {33: System.out.println("File not found.");34: }35: catch (BadDataException exception)36: {37: System.out.println("Bad data: " + exception.getMessage());38: }39: catch (IOException exception)40: {41: exception.printStackTrace();42: }43: }44: }45: }
ch11/data/DataAnalyzer.java (cont.)
COIT11134 - Java Programming 51
• Constructs Scanner object
• Calls readData method
• Completely unconcerned with any exceptions
• If there is a problem with input file, it simply passes the exception to caller
The readFile method of the DataSetReader class
Continued
COIT11134 - Java Programming 52
public double[] readFile(String filename) throws IOException, BadDataException // FileNotFoundException is an IOException { FileReader reader = new FileReader(filename); try { Scanner in = new Scanner(reader); readData(in); } finally { reader.close(); } return data; }
The readFile method of the DataSetReader class (cont.)
COIT11134 - Java Programming 53
• Reads the number of values
• Constructs an array
• Calls readValue for each data value private void readData(Scanner in) throws BadDataException { if (!in.hasNextInt()) throw new BadDataException("Length expected"); int numberOfValues = in.nextInt(); data = new double[numberOfValues];
for (int i = 0; i < numberOfValues; i++) readValue(in, i);
if (in.hasNext()) throw new BadDataException("End of file expected"); }
The readData method of the DataSetReader class
Continued
COIT11134 - Java Programming 54
• Checks for two potential errors • File might not start with an integer • File might have additional data after reading all values
• Makes no attempt to catch any exceptions
The readData method of the DataSetReader class (cont.)
COIT11134 - Java Programming 55
private void readValue(Scanner in, int i) throws BadDataException { if (!in.hasNextDouble()) throw new BadDataException("Data value expected"); data[i] = in.nextDouble(); }
The readValue method of the DataSetReader class
COIT11134 - Java Programming 56
Animation 11.1 –
COIT11134 - Java Programming 57
1.DataAnalyzer.main calls DataSetReader.readFile
2.readFile calls readData
3.readData calls readValue
4.readValue doesn't find expected value and throws BadDataException
5.readValue has no handler for exception and terminates
6.readData has no handler for exception and terminates
7.readFile has no handler for exception and terminates after executing finally clause
8.DataAnalyzer.main has handler for BadDataException; handler prints a message, and user is given another chance to enter file name
Scenario
COIT11134 - Java Programming 58
ch11/data/DataSetReader.java
01: import java.io.FileReader;02: import java.io.IOException;03: import java.util.Scanner;04: 05: /**06: Reads a data set from a file. The file must have the format07: numberOfValues08: value109: value210: . . .11: */12: public class DataSetReader13: {14: /**15: Reads a data set.16: @param filename the name of the file holding the data17: @return the data in the file18: */19: public double[] readFile(String filename) 20: throws IOException, BadDataException21: {22: FileReader reader = new FileReader(filename); Continued
COIT11134 - Java Programming 59
ch11/data/DataSetReader.java (cont.)
23: try 24: {25: Scanner in = new Scanner(reader);26: readData(in);27: }28: finally29: {30: reader.close();31: }32: return data;33: }34: 35: /**36: Reads all data.37: @param in the scanner that scans the data38: */39: private void readData(Scanner in) throws BadDataException40: {41: if (!in.hasNextInt()) 42: throw new BadDataException("Length expected");43: int numberOfValues = in.nextInt();44: data = new double[numberOfValues]; Continued
COIT11134 - Java Programming 60
ch11/data/DataSetReader.java (cont.)
45: 46: for (int i = 0; i < numberOfValues; i++)47: readValue(in, i);48: 49: if (in.hasNext()) 50: throw new BadDataException("End of file expected");51: }52: 53: /**54: Reads one data value.55: @param in the scanner that scans the data56: @param i the position of the value to read57: */58: private void readValue(Scanner in, int i) throws BadDataException59: {60: if (!in.hasNextDouble()) 61: throw new BadDataException("Data value expected");62: data[i] = in.nextDouble(); 63: }64: 65: private double[] data;66: }
Files and Streams
COIT11134 - Java Programming 62
Text and Binary Formats
•Two ways to store data: • Text format • Binary format
COIT11134 - Java Programming 63
Text Format
• Human-readable form
• Sequence of characters • Integer 12,345 stored as characters '1' '2' '3' '4' '5'
• Use Reader and Writer and their subclasses to process input and output
• To read:
FileReader reader = new FileReader("input.txt");
• To write
FileWriter writer = new FileWriter("output.txt");
COIT11134 - Java Programming 64
Binary Format
• Data items are represented in bytes
• Integer 12,345 stored as a sequence of four bytes 0 0 48 57
• Use InputStream and OutputStream and their subclasses
• More compact and more efficient
• To read:
FileInputStream inputStream = new FileInputStream("input.bin");
• To write
FileOutputStream outputStream = new FileOutputStream("output.bin");
COIT11134 - Java Programming 65
Reading a Single Character from a File in Text Format
• Use read method of Reader class to read a single character
• returns the next character as an int • or the integer -1 at end of file
Reader reader = . . .; int next = reader.read(); char c; if (next != -1) c = (char) next;
COIT11134 - Java Programming 66
Reading a Single Character from a File in Binary Format
• Use read method of InputStream class to read a single byte
• returns the next byte as an int • or the integer -1 at end of file
InputStream in = . . .; int next = in.read(); byte b;
if (next != -1) b = (byte) next;
COIT11134 - Java Programming 67
Text and Binary Format
• Use write method to write a single character or byte
• read and write are the only input and output methods provided by the file input and output classes
• Java stream package principle: each class should have a very focused responsibility
• Job of FileInputStream: interact with files and get bytes
• To read numbers, strings, or other objects, combine class with other classes
COIT11134 - Java Programming 68
Self Check 19.1
Suppose you need to read an image file that contains color values for each pixel in the image. Will you use a Reader or an InputStream?
Answer: Image data is stored in a binary format – try loading an image file into a text editor, and you won't see much text. Therefore, you should use an InputStream.
COIT11134 - Java Programming 69
Self Check 19.2
Why do the read methods of the Reader and InputStream classes return an int and not a char or byte?
Answer: They return a special value of -1 to indicate that no more input is available. If the return type had been char or byte, no special value would have been available that is distinguished from a legal data value.
COIT11134 - Java Programming 70
An Encryption Program
• File encryption • To scramble it so that it is readable only to those who know the encryption
method and secret keyword
• To use Caesar cipher • Choose an encryption key – a number between 1 and 25 • Example: If the key is 3, replace A with D, B with E, . . .
• To decrypt, use the negative of the encryption key
COIT11134 - Java Programming 71
To Encrypt Binary Data
int next = in.read(); if (next == -1) done = true; else { byte b = (byte) next; //call the method to encrypt the byte byte c = encrypt(b); out.write(c); }
COIT11134 - Java Programming 72
ch19/caesar/CaesarCipher.java
01: import java.io.InputStream;02: import java.io.OutputStream;03: import java.io.IOException;04: 05: /**06: This class encrypts files using the Caesar cipher.07: For decryption, use an encryptor whose key is the 08: negative of the encryption key.09: */10: public class CaesarCipher11: {12: /**13: Constructs a cipher object with a given key.14: @param aKey the encryption key15: */16: public CaesarCipher(int aKey)17: {18: key = aKey;19: }20:
Continued
COIT11134 - Java Programming 73
ch19/caesar/CaesarCipher.java (cont.)
21: /**22: Encrypts the contents of a stream.23: @param in the input stream24: @param out the output stream25: */ 26: public void encryptStream(InputStream in, OutputStream out)27: throws IOException28: {29: boolean done = false;30: while (!done)31: {32: int next = in.read();33: if (next == -1) done = true;34: else35: {36: byte b = (byte) next;37: byte c = encrypt(b);38: out.write(c);39: }40: }41: }
Continued
COIT11134 - Java Programming 74
ch19/caesar/CaesarCipher.java (cont.)
42: 43: /**44: Encrypts a byte.45: @param b the byte to encrypt46: @return the encrypted byte47: */48: public byte encrypt(byte b)49: {50: return (byte) (b + key);51: }52: 53: private int key;54: }
COIT11134 - Java Programming 75
ch19/caesar/CaesarEncryptor.java
01: import java.io.File;02: import java.io.FileInputStream;03: import java.io.FileOutputStream;04: import java.io.InputStream;05: import java.io.IOException;06: import java.io.OutputStream;07: import java.util.Scanner;08: 09: /**10: This program encrypts a file, using the Caesar cipher.11: */12: public class CaesarEncryptor13: { 14: public static void main(String[] args)15: { 16: Scanner in = new Scanner(System.in);17: try18: { 19: System.out.print("Input file: ");20: String inFile = in.next();21: System.out.print("Output file: ");
Continued
COIT11134 - Java Programming 76
ch19/caesar/CaesarEncryptor.java (cont.)
22: String outFile = in.next();23: System.out.print("Encryption key: ");24: int key = in.nextInt();25: 26: InputStream inStream = new FileInputStream(inFile);27: OutputStream outStream = new FileOutputStream(outFile);28: 29: CaesarCipher cipher = new CaesarCipher(key);30: cipher.encryptStream(inStream, outStream);31: 32: inStream.close();33: outStream.close();34: }35: catch (IOException exception)36: { 37: System.out.println("Error processing file: " + exception);38: }39: }40: }41: 42:
COIT11134 - Java Programming 77
Self Check 19.3
Decrypt the following message: Khoor/#Zruog$.
Answer: It is "Hello, World!", encrypted with a key of 3.
COIT11134 - Java Programming 78
Self Check 19.4
Can you use this program to encrypt a binary file, for example, an image file?
Answer: Yes – the program uses streams and encrypts each byte.
COIT11134 - Java Programming 79
Public Key Encryption
COIT11134 - Java Programming 80
References
Horstmann C. “Big Java”.