Sun Java Solaris Communities My SDN Account Join SDN
 
New to Java Programming Center

New to Java

Programming Center

Java Platform Overview | Getting Started | Step-by-Step Programming
Learning Paths | References & Resources | Certification | Supplements




Contents
BACK<<Getting Started | Handling Exceptions | NEXT>>Creating the Constructor

Where should you write the code to open a file for reading?

The code to open a file should go in a try clause. The code to handle exceptions that might be thrown should go into a catch clause.

For example:

try 
{
// Code that opens a file for reading
} 
catch (Exception e) 
{
// Code to execute if an exception is thrown,
// such as if the file named does not exist.
}

More on Java I/O)
Lesson: I/O: Reading and Writing (but no 'rithmetic)

Class Error

Programming with Java I/O Streams

java.io Documentation

Handling Exceptions

The classes that handle errors and exceptions are objects of the Error or Exception classes for general conditions or errors, or more likely, one of their subclasses for more specific conditions.

The image below shows the hierarchy of the Throwable class, and lists a few of the classes subclassed from the Error and Exception classes. There are many more classes than those listed here, but the diagram demonstrates the general idea.


Throwable Hierarchy

How are you to know which classes to catch? You don't need to memorize these classes. There are a few ways to discover which classes you need to catch and possibly handle in your applications:

  • Look up the classes and methods you are using in your code in the Java API documentation.
  • Get familiar with all the Java classes.
  • Don't try to handle the conditions, and let the compiler tell you which classes to catch and handle.

The last on the list is the easiest and most common way of determining which class or classes to catch. If you call methods from a class that throws an exception, the compiler displays a message letting you know.

For instance, when writing code to read a file and close the file, you may get an error message like the following:

NorthPanel.java:58: unreported exception java.io.I/OException; 
must be caught or declared to be thrown
        br.close();
          ^
1 error

In addition to telling you what kind of exception you need to catch, the compiler lists which method is causing the problem. In this case, I/OException must be caught, and the method that throws this type of exception object is close. In this code, the variable is referring to the BufferedReader class. In the documentation specifically for the close method for BufferedReader it states:

Throws:  I/OException - If an I/O error occurs 

Read what the other methods of this class throw.

After working with Java classes for a while, you'll become familiar with which classes need to be caught and handled, and which you can declare thrown, which you'll learn about later.

Now that you know what kind of error or condition object you need to catch:

  • Write the code you want to try
  • catch the error or condition object
  • Write instructions for how the application is to handle that condition within the catch block

In other words, place the code that can throw an exception in the try clause, and then catch any exceptions that may be thrown in one or more catch clauses.

For instance, here is a defined method that contains code that may cause some condition to occur. Suppose you want to read a file. The pseudo code demonstrates:

public void doReadMethod() {
  try 
     { // Open try clause
     Code that attempts to read a particular file
      } // Close try clause
   // If there is a problem and an exception is thrown:
   catch (IOException ioe) 
      { //Open catch
        System.out.println("An exception was thrown: " + ioe);
      } // Close catch
    }

The catch clause in this example only prints information about the exception to standard output. You can have it do something else, such as pop up a dialog box that gives the user instructions on what to do. You'll see an example of that later.

There is more to exception handling, but for this class and for basic reading from and writing to files, these fundamentals are enough for now.

Java Input and Output

Now that you understand the basics of how error and exception objects are created, thrown, and handled, you can move onto reading from and writing to files.

The java.io package supports data transfer between an application and the console, file, or network. You import this package to applications that need to read from or write data to a file system.

So far you instantiated or created objects for everything in this application from the buttons, to the text fields, to actions and events. Reading from and writing to files also involves objects, specifically objects called streams. Think of streams like the bridges. At one end of the bridge is the starting point object, and at the other a destination object. The bridge is the object a vehicle uses to cross from one side of a body of water to the other. Streams serve a similar function.

The Java platform includes two hierarchies of classes that support streams:

  • byte-oriented input and output
  • character-based input and output

In the use of stream objects, characters or bytes are read or written in sequential order, character by character, or byte by byte. Because the NorthPanel class reads from a file, this section of the tutorial focuses on character-based streams. You learn about byte-oriented streams later in a section on writing objects to files, serializing, and reading them into a GUI.

Character streams can work on input and output to convert each character from the encoding scheme of a native operating system to the Unicode character set used by the Java platform and full support internationalization.


The Stream Process

Reading from a file requires three basic steps:

  1. Associate the file with a File object. (This is not mandatory, but may be useful.) At the least you supply the file or directory name as a String.
  2. Associate the file object with an input stream.
  3. Step through each character or line of the character stream.

What you do with the characters is up to you. You can send them to the console, display them in a GUI, or write them to a file or database. The steps above involve classes that require exception handling as well.

Like creating other objects, you create a stream object by instantiating one of the many stream classes. First, though, you may need information about the file you want to read, such as if the file exists or when it was last modified. To perform checks on a file or directory, associate the file with an instance of the File class:

File f = new File("myfile.txt");

A File class object is an abstract representation of a file and directory pathnames, and has useful methods for making checks on a file, or even creating a directory or file as needed. Here are a few:

  • canRead()
    Tests whether the application can read the file denoted by this abstract pathname.
  • createNewFile()
    Automatically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.
  • delete()
    Deletes the file or directory denoted by this abstract pathname.
  • exists()
    Tests whether the file denoted by this abstract pathname exists.
  • getAbsolutePath()
    Returns the absolute pathname string of this abstract pathname.
  • isFile()
    Tests whether the file denoted by this abstract pathname is a normal file.
  • mkdir()
    Creates the directory named by this abstract pathname.
  • setLastModified(long time)
    Sets the last-modified time of the file or directory named by this abstract pathname.

The documentation contains more methods that are worthy of noting.

You want to read a file into your application, but first you want to check if it can be read. Assuming you have associated the file name with a File object f, how do you check if the file can be read?
   A.  
if (File.canRead())
{
  System.out.println(File + "can be read.");
}
   B.  
if (f.canRead())
{
  System.out.println("File can be read.");
}
   C.   Neither