Download File I/O and Exceptions

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
File I/O and Exceptions
ISE 208: Intermediate Programming
Files
Files provide stable storage between program invocations
Most programs use files for input and/or output
Ex. word processors, games, etc.
Files in Java
Java makes it easy to work with files
We can use Scanner to read from files the same way that
we use it to read from standard input
This is much easier than what Java 1.4 and earlier required...
The File class is used to open and manipulate a data file
Once we open a file, we pass it to Scanner for reading
The File Class
Defined in the java.io package
Usage:
File foo = new File(“input.txt”);
The File constructor takes a String containing the path to
the file
This path can be relative or absolute
Reading From a File
try
{
File f = new File(“input.txt”);
Scanner s = new Scanner(f);
// call Scanner methods to read input
}
catch (IOException ioe)
{}
Writing to a File
This is slightly more complicated than reading from a file; two
classes are necessary
We’ll cover the case of writing to a text file (rather than a
binary file)
Strategy: use the PrintWriter and FileWriter utility
classes to send data to the output file
PrintWriter collects the data to be sent
FileWriter actually adds the data to the file
PrintWriter
This class provides special print() and println() methods
When we create a PrintWriter, we specify where it should
send the data it collects
PrintWriter stores the data we send it in a buffer
Data isn’t sent immediately; it is held until the buffer is full
When the buffer is full, PrintWriter flushes (empties) its
buffer and sends the data on to its destination
We can also tell PrintWriter to flush its buffer after each write
FileWriter
FileWriter is a subclass of OutputStreamWriter
A FileWriter object writes bytes to a file (specified when
you create the FileWriter)
We can also specify whether we want to append to the file, or
overwrite it, if the file already exists
The FileWriter object is passed as an argument to the
PrintWriter constructor
Writing To A File
try
{
File f = new File(“output.txt”);
// The second argument to FileWriter’s constructor determines what
// happens if f already exists.
// true: append to the file, false: replace the original file
FileWriter fw = new FileWriter(f, true);
// Passing a second boolean argument to PrintWriter’s constructor
// sets whether the buffer will be flushed after each write operation
PrintWriter pw = new PrintWriter(fw);
pw.println(“Hello, world!”); // Add more data to PrintWriter’s buffer
pw.flush();
// Send buffer contents to the FileWriter
}
catch (IOException ioe) {
}
Try...Catch Blocks
try...catch blocks are used to handle exceptions
An exception is an abnormal event that occurs during program
execution
Ex. nonexistent files, division by zero
Try blocks surround code that may generate (raise) an exception
Catch blocks are called when a particular type of exception
occurs
They give us the opportunity to recover from the problem
Types of Exceptions
The Exception class has many subclasses:
FileNotFoundException
ArrayIndexOutOfBoundsException
NullPointerException
Generally, these subclasses are identical to the Exception
class; they allow us to distinguish different types of exceptions
You can also subclass Exception for your own programs
More on Exception Types
Exceptions fall into two main categories:
Checked: the Java compiler specifically verifies that your code
has try...catch blocks to handle these exceptions
Ex. IOException
Unchecked: you may, but are not required to, add try...catch
blocks to guard against these types of exceptions
Ex. ArrayIndexOutOfBoundsException,
NullPointerException
Raising an Exception
To raise an exception, use the throw keyword:
if (filename.equals(“badfile.txt”))
throw new Exception(“Bad filename!”);
throw passes the exception to the first available handler
A handler is a catch block that checks for the type of
exception that has been thrown
Different handlers can check for different exception types
The handler may be in a different method, or even class
Handling Exceptions
If an exception occurs in a piece of code and an exceptionhandler is available, flow of control passes to the handler
When the handler has completed its work, execution
continues from the point a"er the handler code
Control does not return to the code that generated the
exception
If a block of code does not have a catch block to handle
the exception, the exception is passed (propagated) along the
call stack, looking for an appropriate handler.
Unhandled Exceptions
Every exception must be caught
Uncaught exceptions will eventually propagate all the way
back to the JVM, which will terminate the program
The JVM prints an error message (called a stack trace) showing
you the contents of the call stack when the exception occurred:
Exception in thread "main"
java.lang.NullPointerException
at java.lang.Integer.compareTo(Integer.java:928)
at IntegerSorter.sortArray(IntegerSorter.java:49)
at TestHarness3.main(TestHarness3.java:39)
Try...Catch, Revisited
A try...catch block is used to wrap code that may generate
an exception
If the wrapped code does not generate any exceptions, the
catch block is completely ignored
If an exception occurs, the try block ends immediately, and
execution shifts to the catch block
The catch block has code to recover from the exception
When the catch block finishes, execution continues after
that block; we don’t resume execution in the try block
try
{
// Execution begins here, and continues
// until the end of the block is reached,
// or an exception occurs
}
catch ( exception object declaration)
{
exception recovery code
}
Try and Finally
If an exception occurs, the rest of the code in the try block is
ignored
Execution resumes a"er the catch block
To make sure statements are executed regardless of an exception,
use a finally block
Code in a finally block is always executed after the try or
catch block completes
This may mean returning to the method where the exception
occurred
try
{
// Execution always starts here...
}
catch ( exception )
{
// Executes if an exception occurs
}
finally
{
// Code that always executes
}
Multiple Catch Blocks
A try block can be followed by several catch blocks
Each catch block specializes in a different type of exception
Ex. IOException vs. ArithmeticException
Execution passes to the first catch block that advertises the
ability to handle the exception
For this reason, the catch blocks must be ordered from the
most specific (subclasses) to the least specific (superclasses)
Ordering is irrelevant for sibling Exception subclasses
Good Ordering
try
{ }
catch (FileNotFoundException f) // more specific (subclass)
{ }
catch (IOException i) // less specific (superclass)
{ }
Bad Ordering
try
{ }
catch (IOException i)
{ }
// Less specific (superclass)
catch (FileNotFoundException f) // More specific (subclass)
{
// This catch will never be executed! The IOException catch
// block can handle FileNotFoundExceptions and more...
}
Passing The Buck
A method does not have to handle its own exceptions
It can throw the exception (to the calling method) instead
To indicate this, the method must add throws to its header:
public void foo () throws IOException
The client needs a try...catch structure to deal with the
exception (or throw the exception to its own caller)
A method may throw multiple exception types
Remaining Topics
Recursion
GUI Programming and Applets
Linked Lists