0% found this document useful (0 votes)
63 views6 pages

09 File Io and Exceptions

Files provide stable storage between program invocations. Most programs use files for input and/or output, such as word processors, games, etc. In Java, the File class represents files and directories on the file system and allows reading, writing, and other file operations. The File class is used to open and manipulate data files, and once a file is opened it can be passed to a Scanner for reading or a PrintWriter and FileWriter for writing. Try-catch blocks are used to handle exceptions that may occur during file input/output operations.

Uploaded by

urbedglvbh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
0% found this document useful (0 votes)
63 views6 pages

09 File Io and Exceptions

Files provide stable storage between program invocations. Most programs use files for input and/or output, such as word processors, games, etc. In Java, the File class represents files and directories on the file system and allows reading, writing, and other file operations. The File class is used to open and manipulate data files, and once a file is opened it can be passed to a Scanner for reading or a PrintWriter and FileWriter for writing. Try-catch blocks are used to handle exceptions that may occur during file input/output operations.

Uploaded by

urbedglvbh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
You are on page 1/ 6

Files

Files provide stable storage between program invocations

Most programs use files for input and/or output


File I/O and Exceptions Ex. word processors, games, etc.
CSE 114: Computer Science I
Stony Brook University

Files in Java The File Class


Java makes it easy to work with files Defined in the java.io package
We can use Scanner to read from files the same way that Usage:
we use it to read from standard input
File foo = new File(“input.txt”);
This is much easier than what Java 1.4 and earlier required...
The File constructor takes a String containing the path
The File class is used to open and manipulate a data file to the file

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

FileWriter actually adds the data to the file

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

Types of Exceptions More on Exception Types


Exceptions fall into two main categories:
The Exception class has many subclasses:
Checked: the Java compiler specifically verifies that your code
FileNotFoundException
has try...catch blocks to handle these exceptions
ArrayIndexOutOfBoundsException
Ex. IOException
NullPointerException
Unchecked: you may, but are not required to, add try...catch
Generally, these subclasses are identical to the Exception blocks to guard against these types of exceptions
class; they allow us to distinguish different types of exceptions
Ex. ArrayIndexOutOfBoundsException,
You can also subclass Exception for your own programs NullPointerException
Raising an Exception Handling Exceptions
To raise an exception, use the throw keyword: If an exception occurs in a piece of code and an exception-
handler is available, flow of control passes to the handler
if (filename.equals(“badfile.txt”))
throw new Exception(“Bad filename!”); When the handler has completed its work, execution
continues from the point a!er the handler code
throw passes the exception to the first available handler
Control does not return to the code that generated the
A handler is a catch block that checks for the type of
exception
exception that has been thrown
If a block of code does not have a catch block to handle
Different handlers can check for different exception types
the exception, the exception is passed (propagated) along the
The handler may be in a different method, or even class call stack, looking for an appropriate handler.

Unhandled Exceptions Try...Catch, Revisited


Every exception must be caught A try...catch block is used to wrap code that may generate
an exception
Uncaught exceptions will eventually propagate all the way
back to the JVM, which will terminate the program If the wrapped code does not generate any exceptions, the
catch block is completely ignored
The JVM prints an error message (called a stack trace) showing
you the contents of the call stack when the exception occurred: If an exception occurs, the try block ends immediately, and
execution shifts to the catch block
Exception in thread "main"
java.lang.NullPointerException

The catch block has code to recover from the exception
at java.lang.Integer.compareTo(Integer.java:928)

at IntegerSorter.sortArray(IntegerSorter.java:49)

When the catch block finishes, execution continues after
at TestHarness3.main(TestHarness3.java:39)
that block; we don’t resume execution in the try block
try
Try and Finally
{ If an exception occurs, the rest of the code in the try block is
// Execution begins here, and continues ignored
// until the end of the block is reached,
// or an exception occurs Execution resumes a!er the catch block
} To make sure statements are executed regardless of an
catch ( exception object declaration)
exception, use a finally block
{
exception recovery code 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
{ 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)

Ordering is irrelevant for sibling Exception subclasses


Good Ordering Bad Ordering
try
try
{ } { }

catch (FileNotFoundException f) // more specific (subclass)
{ } catch (IOException i) // Less specific (superclass)
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

You might also like