Java Programming Week 9: Input/Ouput and Exception Handling, Files and Streams (Chapter 11 and Chapter 19)

Slides:



Advertisements
Similar presentations
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Advertisements

Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
COMP 121 Week 5: Exceptions and Exception Handling.
Chapter 9 Exception Handling. Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference.
When you use an input or output file that does not exist, what will happen? −The compiler insists that we tell it what the program should do in such case.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Catching Exceptions An exception may be thrown by a method when an exceptional occurance happens (and the method does not have the expertise to remedy.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Chapter 11.  Data is often stored in files such as a text file  We need to read that data into our program  Simplest mechanism  Scanner class  First.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 11 – Input/Output and Exception Handling.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
Chapter 11  I/O and Exception Handling 1 Chapter 11 I/O and Exception Handling.
Exception Handling. Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between.
Lecture 7 File I/O (and a little bit about exceptions)‏
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Files and Streams CS 21a Chapter 11 of Horstmann.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Chapter 8 Overview – Learn to use try catch blocks – Learn to use streams – Learn to use text files.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Eleven: Input/Ouput and Exception Handling.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Chapter 20 – Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Input/Output and Exception Handling.
Two Ways to Store Data in a File Text format Binary format.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 11 – Input/Output and Exception Handling.
Chapter 16 Streams. Chapter Goals To be able to read and write text files To become familiar with the concepts of text and binary formats To learn about.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Exceptions Handling the unexpected. RHS – SWC 2 The Real World So far, most of our code has been somewhat näive We have assumed that nothing goes wrong…
Fall 2006Adapted from Java Concepts Companion Slides1 Files and Streams Advanced Programming ICOM 4015 Lecture 16 Reading: Java Concepts Chapter 16.
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
CSE 501N Fall ‘09 18: Files and Streams 06 November 2009 Nick Leidenfrost.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Chapter 14 Exception Handling. Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference.
CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Chapter 10 – Input/Output and Exception Handling Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Week 12 – Text Files Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Input/Output and Exception Handling.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Exception Handling.
Introduction Exception handling Exception Handles errors
CSE 501N Fall ’09 17: Exception Handling
Chapter 11 – Input/Output and Exception Handling
Goals To read and write text files To process command line arguments
Chapter 11 – Input/Output and Exception Handling
Chapter 15 – Exception Handling
Advanced Java Programming
Exceptions Handling the unexpected
CSS 161: Fundamentals of Computing
Exception Handling.
Fundamental Error Handling
Chapter 16 Streams.
Chapter 11 Input/Output Exception Handling
Chapter 12 Exception Handling and Text IO Part 1
Presentation transcript:

Java Programming Week 9: Input/Ouput and Exception Handling, Files and Streams (Chapter 11 and Chapter 19)

COIT Java Programming2 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

COIT Java Programming3 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

COIT Java Programming4 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

COIT Java Programming5 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

COIT Java Programming6 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

COIT Java Programming7 01: import java.io.FileReader; 02: import java.io.FileNotFoundException; 03: import java.io.PrintWriter; 04: import java.util.Scanner; 05: 06: public class LineNumberer 07: { 08: public static void main(String[] args) 09: throws FileNotFoundException 10: { 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

COIT Java Programming8 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.)

COIT Java Programming9 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.

COIT Java Programming10 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.

COIT Java Programming11 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

COIT Java Programming12 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

COIT Java Programming13 public class BankAccount { public void withdraw(double amount) { if (amount > balance) { IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; } balance = balance - amount; }... } Example

COIT Java Programming14 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

COIT Java Programming15 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.

COIT Java Programming16 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.

COIT Java Programming17 Hierarchy of Exception Classes

COIT Java Programming18 Two types of exceptions: Checked oThe compiler checks that you don't ignore them oDue to external circumstances that the programmer cannot prevent oMajority occur when dealing with input and output oFor example, IOException Checked and Unchecked Exceptions

COIT Java Programming19 Unchecked: oExtend the class RuntimeException or Error oThey are the programmer's fault oExamples of runtime exceptions: NumberFormatException IllegalArgumentException NullPointerException oExample of error: OutOfMemoryError Checked and Unchecked Exceptions

COIT Java Programming20 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

COIT Java Programming21 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

COIT Java Programming22 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.)

COIT Java Programming23 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

COIT Java Programming24 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.

COIT Java Programming25 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.

COIT Java Programming26 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

COIT Java Programming27 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.)

COIT Java Programming28 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

COIT Java Programming29 try { statement statement... } catch (ExceptionClass exceptionObject) { statement statement... } catch (ExceptionClass exceptionObject) { statement statement... }... Syntax 11.3 General Try Block Continued

COIT Java Programming30 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

COIT Java Programming31 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.)

COIT Java Programming32 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.

COIT Java Programming33 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 Recall that IOException is a checked exception and NumberFormatException is an unchecked exception.

COIT Java Programming34 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

COIT Java Programming35 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

COIT Java Programming36 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

COIT Java Programming37 try { statement statement... } finally { statement statement... } Syntax 11.4 The finally Clause Continued

COIT Java Programming38 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 } COIT Java Programming39

COIT Java Programming40 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.

COIT Java Programming41 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

COIT Java Programming42 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

COIT Java Programming43 public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() {} public InsufficientFundsException(String message) { super(message); } } Designing Your Own Exception Types

COIT Java Programming44 What is the purpose of the call super(message ) in the second InsufficientFundsException constructor? Self Check Answer: To pass the exception message string to the RuntimeException superclass.

COIT Java Programming45 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 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.

COIT Java Programming46 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: A Complete Example

COIT Java Programming47 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

COIT Java Programming48 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.)

COIT Java Programming49 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, an 08: error message is displayed. 09: */ 10: public class DataAnalyzer 11: { 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

COIT Java Programming50 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.)

COIT Java Programming51 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

COIT Java Programming52 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.)

COIT Java Programming53 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

COIT Java Programming54 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.)

COIT Java Programming55 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

COIT Java Programming56 Animation 11.1 –

COIT Java Programming57 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

COIT Java Programming58 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 format 07: numberOfValues 08: value1 09: value2 10:... 11: */ 12: public class DataSetReader 13: { 14: /** 15: Reads a data set. filename the name of the file holding the data the data in the file 18: */ 19: public double[] readFile(String filename) 20: throws IOException, BadDataException 21: { 22: FileReader reader = new FileReader(filename); Continued

COIT Java Programming59 ch11/data/DataSetReader.java (cont.) 23: try 24: { 25: Scanner in = new Scanner(reader); 26: readData(in); 27: } 28: finally 29: { 30: reader.close(); 31: } 32: return data; 33: } 34: 35: /** 36: Reads all data. in the scanner that scans the data 38: */ 39: private void readData(Scanner in) throws BadDataException 40: { 41: if (!in.hasNextInt()) 42: throw new BadDataException("Length expected"); 43: int numberOfValues = in.nextInt(); 44: data = new double[numberOfValues]; Continued

COIT Java Programming60 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. in the scanner that scans the data i the position of the value to read 57: */ 58: private void readValue(Scanner in, int i) throws BadDataException 59: { 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

COIT Java Programming62 Text and Binary Formats Two ways to store data: Text format Binary format

COIT Java Programming63 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");

COIT Java Programming64 Binary Format Data items are represented in bytes Integer 12,345 stored as a sequence of four bytes 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");

COIT Java Programming65 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;

COIT Java Programming66 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;

COIT Java Programming67 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

COIT Java Programming68 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.

COIT Java Programming69 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.

COIT Java Programming70 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

COIT Java Programming71 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); }

COIT Java Programming72 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 CaesarCipher 11: { 12: /** 13: Constructs a cipher object with a given key. aKey the encryption key 15: */ 16: public CaesarCipher(int aKey) 17: { 18: key = aKey; 19: } 20: Continued

COIT Java Programming73 ch19/caesar/CaesarCipher.java (cont.) 21: /** 22: Encrypts the contents of a stream. in the input stream out the output stream 25: */ 26: public void encryptStream(InputStream in, OutputStream out) 27: throws IOException 28: { 29: boolean done = false; 30: while (!done) 31: { 32: int next = in.read(); 33: if (next == -1) done = true; 34: else 35: { 36: byte b = (byte) next; 37: byte c = encrypt(b); 38: out.write(c); 39: } 40: } 41: } Continued

COIT Java Programming74 ch19/caesar/CaesarCipher.java (cont.) 42: 43: /** 44: Encrypts a byte. b the byte to encrypt the encrypted byte 47: */ 48: public byte encrypt(byte b) 49: { 50: return (byte) (b + key); 51: } 52: 53: private int key; 54: }

COIT Java Programming75 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 CaesarEncryptor 13: { 14: public static void main(String[] args) 15: { 16: Scanner in = new Scanner(System.in); 17: try 18: { 19: System.out.print("Input file: "); 20: String inFile = in.next(); 21: System.out.print("Output file: "); Continued

COIT Java Programming76 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:

COIT Java Programming77 Self Check 19.3 Decrypt the following message: Khoor/#Zruog$. Answer: It is "Hello, World!", encrypted with a key of 3.

COIT Java Programming78 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.

COIT Java Programming79 Public Key Encryption

COIT Java Programming80 References Horstmann C. “Big Java”.