Files and GUIs

This is the barest introduction to using the pre-defined GUI dialogs for selecting files. The classes involved can be used in much more sophisticated ways, but learning how would require more time than we have remaining.

The simple recipe

  1. Construct a JFileChooser when you are initializing the program. When you want to show a dialog, call either showOpenDialog() or showSaveDialog(). Those methods return a numeric code to indicate the outcome; the value to check for is JFileChooser.APPROVE OPTION.
  2. If a file was selected, call the getSelectedFile() method to get a result of type File, which is the way that the Java library encapsulates filenames.
  3. To open the File for reading, pass it to the constructor for FileInputStream.
    To open for writing, pass it to the constructor for PrintWriter.
  4. You can also call getName() or getPath() on the File instance to get a String representation of the name.

Exceptions

Keep in mind that opening a file can throw an exception. The most likely exception you will see is java.io.FileNotFoundException, a subtype of java.io.IOException.

Remember also that reading or writing an open file can also throw an IOException. Methods that do those operations must either be declared to throw that exception, or they should include a try with an appropriate catch clause. The reason may not be obvious to you, but the close()’ method can also throw an IOException .

For programs that are not trivial, it is important to remember to close any file that you open. A good way to do that is to wrap the code that processes the file in a try...finally. What this means in practice is that file processing usually looks something like this:

    ... get a filename or File ...
    InputStream f;
    try {
      f = new InputStream(...name or File...);
    }
    catch (IOException e) {
      ... deal with the failure ...
    }

    try {
        ... process the file ...
    }
    finally {
        f.close();
    }

There might also be a catch clause on the second try block, or there might be another try block inside that to deal with read errors.

Note that the method close() can throw an IOException. So you will need to put a try block in the finally clause, or put the entire second try block inside another try to catch that.