09 File Io and Exceptions
09 File Io and Exceptions
Once we open a file, we pass it to Scanner for reading This path can be relative or absolute
Reading From a File Writing to a File
try This is slightly more complicated than reading from a file; two
{ classes are necessary
File f = new File(“input.txt”);
Scanner s = new Scanner(f); We’ll cover the case of writing to a text file (rather than a
binary file)
// call Scanner methods to read input
} Strategy: use the PrintWriter and FileWriter utility
catch (IOException ioe) classes to send data to the output file
{}
PrintWriter collects the data to be sent
PrintWriter FileWriter
This class provides special print() and println() methods FileWriter is a subclass of OutputStreamWriter
When we create a PrintWriter, we specify where it should A FileWriter object writes bytes to a file (specified when
send the data it collects you create the FileWriter)
PrintWriter stores the data we send it in a buffer We can also specify whether we want to append to the file, or
overwrite it, if the file already exists
Data isn’t sent immediately; it is held until the buffer is full
The FileWriter object is passed as an argument to the
When the buffer is full, PrintWriter flushes (empties) its PrintWriter constructor
buffer and sends the data on to its destination
We can also tell PrintWriter to flush its buffer after each write
Writing To A File Try...Catch Blocks
try
{
try...catch blocks are used to handle exceptions
File f = new File(“output.txt”);
An exception is an abnormal event that occurs during
// The second argument to FileWriter’s constructor determines what
// happens if f already exists.
program execution
// true: append to the file, false: replace the original file
FileWriter fw = new FileWriter(f, true);
Ex. nonexistent files, division by zero
// Passing a second boolean argument to PrintWriter’s constructor
// sets whether the buffer will be flushed after each write operation Try blocks surround code that may generate (raise) an
PrintWriter pw = new PrintWriter(fw);
exception
pw.println(“Hello, world!”); // Add more data to PrintWriter’s buffer
pw.flush(); // Send buffer contents to the FileWriter Catch blocks are called when a particular type of exception
}
catch (IOException ioe) { } occurs
try
{ Multiple Catch Blocks
// Execution always starts here...
} A try block can be followed by several catch blocks
catch ( exception ) Each catch block specializes in a different type of exception
{
// Executes if an exception occurs Ex. IOException vs. ArithmeticException
} Execution passes to the first catch block that advertises the
finally ability to handle the exception
{
// Code that always executes For this reason, the catch blocks must be ordered from the
} most specific (subclasses) to the least specific (superclasses)