36
File I/O & error-handling Crash course

O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

  • Upload
    others

  • View
    17

  • Download
    0

Embed Size (px)

Citation preview

Page 1: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

File I/O & error-handling

Crash course

Page 2: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Ensuring reliability

• We do our best to ensure program correctness through a rigorous testing and debugging process

• To ensure reliability, we must anticipate conditions that could cause problems, and try to deal with them before the problems occur

• In Java, we have exception handling, a powerful tool for ensuring program reliability

Page 3: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Exceptions

• An error condition that occurs during program runtime is called an exception

• Exceptions are represented by exception objects, which are generated (thrown) in response to error conditions

• Java includes a rich set of routines for dealing with such circumstances: this is known as exception handling

Page 4: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Catching exceptions: try/catch block

• Consists of try block followed by one or more catch blocks

– try block: encloses code that might throw an exception

– catch block(s) deal with any exception(s) thrown

Page 5: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Syntax for try/catch block

try {// code that may throw an exception

} catch (ExceptionType parameterName) {// code that handles an exception thrown // in the try block

}

Page 6: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Catching Exceptions

• Statements in the try block are executed in sequence.

• If no error occurs then no exception is thrown, all statements in the try block are executed and the catch block(s) will be skipped

Page 7: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Catching Exceptions

• When one of the statements throws an exception, control is passed to the matching catch block and statements inside the catch block are executed

• Provided the catch block does not halt the program or return from the method, program execution continues at the first statement following the catch block

• If more than one exception is possible, multiple catch blocks can be written

Page 8: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Example

int value; // number to be supplied by userString input; // value read from keyboardScanner kb = new Scanner (System.in);

System.out.print (“Enter a number: ”);input = kb.nextLine();

try {value = Integer.parseInt(input);

} catch (NumberFormatException e) {System.out.println (input + “is not valid.\n” +

“Please enter digits only.”);}

Page 9: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Example – assumes existence of instance variable kb and constants UPPER and LOWER

public int getNumData (String prompt) {String inputStr;int num;while (true) {

System.out.print(prompt);inputStr = kb.nextLine(); try {

num = Integer.parseInt(inputStr);if (num < LOWER || num > UPPER)

throw new Exception("Input out of bounds");return num; // input okay so return the value & exit, ending loop

} catch (NumberFormatException e) {System.out.println(inputStr + " is invalid\n" + "Please enter digits only");

} catch (Exception e) {System.out.println(e.getMessage());

} // end catch block} // end while loop

} // end method

Page 10: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Checked & unchecked exceptions

• There are two general types of exceptions that may occur within programs:

– checked exceptions are those that must be accounted for or the program won’t compile

– unchecked exceptions are those that the compiler doesn’t account for; hence the name

• Most of the exceptions we have discussed so far have been unchecked exceptions

Page 11: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Not catching exceptions

• As stated on the previous slide, there are some types of exceptions that we must handle in order for our programs to compile

• There are times when we may not wish to catch exceptions in our code, but are forced to deal with them because they are checked

• In such a situation, a throws clause can be used instead of a try/catch block

Page 12: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Example

• Suppose you have a method that appears to you to be coded correctly, but the compiler keeps coming back with an error message like the following:unreported exception java.lang.InterruptedException; must

be caught or declared to be thrown

• This message results from an attempt to compile a method with a checked exception that has not been handled

Page 13: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Example

The class shown below contains a main method that would produce the compiler message shown on the previous slide:

public class ThreadTest{

public static void main(String [] args) {Thread.sleep(100);System.out.println ("2");

}}

One way to take care of the exception and get rid of the error message is shown on the following slide

Page 14: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Example

public class ThreadTest{

public static void main(String [] args) throws InterruptedException {

System.out.println ("1");Thread.sleep(100);System.out.println ("2");

}}

The “throws clause,” which is part of the method heading, simply indicates that we acknowledge that an exception might occur, and that it will be handled elsewhere. This is the default behavior with unchecked exceptions; we only have to add a throws clause if our code could throw a checked exception.

Page 15: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Text file I/O

• We’ll begin by looking at the simplest case: writing text data to a file

• When you intend to read or write files, you will need to use classes and methods from the java.io package, so begin with the following import statement:

import java.io.*;

Page 16: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

PrintWriter and FileOutputStream

• An object of type PrintWriter is the preferred means to represent a text file output stream,

• The PrintWriter constructor requires a parameter of type FileOutputStream, which in turn has a constructor that requires a String parameter, specifiying a file name

• Constructing a PrintWriter object on a specific FileOutputStream is called opening a file

Page 17: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Example – opening an output file

• I want to write some data to a file in the same folder as my program’s byte code; the file name is MyData.txt

• I could use the following syntax to open the file (by creating a PrintWriter object named myFile):

PrintWriter myFile = new PrintWriter(new

FileOutputStream(“MyData.txt”));

Page 18: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Breaking down the example

• On the previous slide, two objects were created:

– an anonymous FileOutputStream object

– a PrintWriter object

• In creating the first object, a FileNotFoundException (a subtype of IOException) can be thrown – this is a checked exception, so it must be handled with either a try/catch block or a throws clause

Page 19: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Variation on example

• It makes sense to use an anonymous FileOutputStream object (because it isn’t used anywhere else in the program) to create the PrintWriter object

• However, it is really the creation of the FileOutputStream that throws the exception, and we could isolate just this line of code if we wanted to place it in a try block, as shown on the next slide

Page 20: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Variation on exampleScanner kb = new Scanner(System.in);

String fileName;

System.out.print (“Enter name for output file: “);

fileName = kb.nextLine();

PrintWriter myFile;

FileOutputStream myStream;

try {

myStream = new FileOutputStream(fileName);

} catch (FileNotFoundException e) {

System.out.println (“File could not be opened for output; closing program”);

System.exit(1);

} // ends catch block

myFile = new PrintWriter(myStream);

Page 21: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Writing output to text files

• Once a PrintWriter object has been instantiated, writing output to an open file is as simple as writing output to the screen

• The methods print, println, and printf can be called on the PrintWriter object, just as they can be called on System.out

• You can still call these same methods from System.out, so you can write to either a file or the screen in the same program

Page 22: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Other PrintWriter methods

• The close() method closes the stream’s connection to a file; it should be called before ending a program with an open file

• Note that the same PrintWriter object can be used to open multiple files – you just have to close one file before you open another

• If you wish to write to a file and read from it later, you must close it as an output file before opening it as an input file

• The flush() method can be called to force a write to a file – this will clear the output buffer of all data currently in it

Page 23: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Exampleimport java.io.*;

import java.util.*;

public class WriteMyFile {

public static void main (String [] args) throws FileNotFoundException {

Scanner kb = new Scanner(System.in);

String fName;

System.out.print(“Enter output file name:”);

fName = kb.nextLine();

PrintWriter pw = new PrintWriter(new FileOutputStream(fName));

System.out.println(“Here it is on the screen”);

pw.println(“And here it is in the file”);

pw.close();

}

}

Page 24: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Overwriting vs. appending to output files

• The way you open a file (by calling the FileOutputStream constructor) determines whether you will create a new file, overwrite an existing file, or add contents to an existing file

• If you call the constructor as we have been doing, with a single String argument, you will either create a new file or overwrite an existing one – the latter if a file by the specified name already exists

• If you call the constructor with two arguments – a String and a true boolean expression – you will instead open the file to append to it, rather than replace it

Page 25: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Example

• Suppose the file created in the WriteMyFile example exists in the root directory of drive A and contains the text “And here it is in the file”

• The following code:PrintWriter pw = new PrintWriter (new

FileOutputStream(“A:\\myFile.txt”, true));

pw.println(“And here we go again”);

pw.close();

would add text to the file; its contents would now be:And here it is in the file

And here we go again

Page 26: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

General notes on examples

• All of the examples so far have opened a file, written a single line to it, then closed the file

• The examples are set up as they are to keep them short – they aren’t typical

• Normally, we would write several lines of output to a file, first opening it, then closing it when our output is finished

• In general, a file output stream is just like the standard output stream – we just have to remember to open it before we can use it, and close it when we’re done

Page 27: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Reading input from a text file

• Can use the same Scanner class we use for keyboard input to read from a text file

• When reading from the keyboard, we create the Scanner object by passing its constructor an object representing the standard input stream:Scanner kb = new Scanner (System.in);

• To read from a test file, we construct it by passing a FileInputStream object instead – in other words, we open an input file much the same way we open an output file

Page 28: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Syntax & example

• General syntax:

Scanner scanner = new Scanner

(new FileInputStream(name));

• Example:

Scanner input = new Scanner

(new FileInputStream(“C:\\myfiles\\data.txt”));

Page 29: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Notes on opening input files

• Instantiating a FileInputStream object can throw the same type of exception (FileNotFoundException) as with a FileOutputStream object

• As with output files, we can break down the process of opening an input file into smaller pieces; see next slide

Page 30: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Example

String fileName;

Scanner kb = new Scanner (System.in);

System.out.print(“Enter name of input file: ”);

fileName = kb.nextLine();

FileInputStream inFileStream;

try {

inFileStream = new FileInputStream(fileName);

} catch (FileNotFoundException e) {

System.out.println(“Could not open input file – ending program”);

System.exit(1);

}

Scanner inFile = new Scanner(inFileStream);

Page 31: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Scanner methods

• Once a Scanner object is open, you can call the same methods to read data from an input file as you have used to read data from the keyboard

– for integers: nextInt()

– for doubles: nextDouble()

– for Strings: next() and nextLine()

Page 32: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

More Scanner methods

• The Scanner class has several “look ahead” methods that can be used to determine:

– whether or not there is more input to come

– the nature of the input (number vs. text)

• All of the following methods return a boolean value:

– hasNextInt()

– hasNextDouble()

– hasNext()

Page 33: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Exampleimport java.util.*;

public class IOTest {

public static void main (String [] args) {

Scanner kb = new Scanner (System.in);

boolean end = false;

while (!end) {

System.out.print("Enter some text; enter a number to quit: ");

if (kb.hasNextDouble())

end = true;

else {

String input = kb.nextLine();

System.out.println ("You entered: " + input);

}

}

}

}

Page 34: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

File input & EOF loops

• The previous example used the difference between text and numeric input to determine the end of keyboard data

• A more realistic, and much more common application, is the use of the hasNext() method(s) to determine whether or not there is more data to be read from a file

Page 35: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

Example

Scanner inFile = new Scanner (new FileInputStream(“somefile.txt”));

String input;

while (inFile.hasNextLine())

{

input = inFile.nextLine();

// processing of input can occur here

}

inFile.close();

Page 36: O & error-handling - Kirkwood Community College · exception handling. Catching exceptions: try/catch block •Consists of try block followed by one or more catch blocks –try block:

File objects

• As far as Java is concerned, files and folders are the same thing

• The File object defined in the API contains methods for manipulating files, and is useful for input of non-text data (e.g. pictures)