Concepts / Using File Dialog Boxes

Using File Dialog Boxes

JFileChooser creates file dialogs that let a user choose a file for reading or writing instead of typing a path.

  • Programming

Choosing a File Without Typing a Path

A program that reads or writes a file needs to know which file to use. One approach is to have the user type a full file path by hand. That works, but it puts the burden on the user to remember the exact location and spell the name correctly. A file dialog box solves this by showing the user a window where they can browse folders, see the files that exist, and pick one with the mouse.

In Java, the class that creates these dialogs is JFileChooser. This article follows a mechanism rather than a finished application. As you read, keep one question in mind: what does the program do before the dialog appears, what does it do while the dialog is open, and what does it do once the user closes it?

What JFileChooser Does

Definition

JFileChooser creates file dialogs that let a user choose a file for reading or writing instead of typing a path.

The same class serves both directions of file work. A single JFileChooser can be used to pick a file the program will read and to pick a file the program will write. What changes between the two uses is which method the code calls to show the dialog, and how the dialog is set up before it appears.

Two Dialog Methods: Open and Save

The source uses two methods, readFile() and writeFile(), and both work with a JFileChooser object. The method readFile() shows its dialog with showOpenDialog(this). The method writeFile() shows its dialog with showSaveDialog(this). The name of the method that displays the dialog tells you the purpose: one is for opening a file the program will read, and the other is for saving a file the program will write.

FeatureReading (readFile)Writing (writeFile)
Method that shows the dialogshowOpenDialog(this)showSaveDialog(this)
Dialog titleSelect File for ReadingSelect File for Writing
Initially selected fileNone (setSelectedFile(null))output.txt
Check on the return valueReturns early if canceled or closedReturns early if canceled or closed

Differences between the two dialog setups in the source

Tracing the Dialog's Return Value

What do you think happens?

When the program needs a file to write, which method does it call to show the dialog?

  • showOpenDialog(this)

  • showSaveDialog(this)

Reveal answer
Answer:

showSaveDialog(this)

The source's writeFile() method shows its dialog with showSaveDialog(this), while readFile() uses showOpenDialog(this).

Once the dialog is shown, the program does not immediately act on the file. Both methods check the dialog's return value, and both return early if the user canceled or closed the dialog. In other words, the file code that follows the dialog is only reached when the user has actually made a choice. The diagram below traces this path. Read it from the top: the dialog is shown, the user responds, and the response decides which branch the program takes.

Show dialogshowOpenDialog orshowSaveDialogUser responseCanceled or closedReturn earlyfile code skippedFile chosenFile code runsdialog closescanceledapproved
After the user closes the dialog, which path runs and which is skipped, depending on whether they chose a file or canceled?

Think of the return value as a gate. If the user cancels, the gate closes and the method leaves before any file work starts. If the user approves a file, the gate opens and the code that uses the chosen file runs. This is why a canceled dialog does not produce an error in the file code: the code never reaches the part that would need a file.

Checking for an Existing File Before Writing

After the user approves the save dialog, writeFile() gets the chosen file with getSelectedFile(). It then calls selectedFile.exists() to check whether a file with that name is already present. If the file exists, the code calls JOptionPane.showConfirmDialog to ask the user whether to replace it. The message shown includes the file name, and the source's text reads: "The file already exists. Do you want to replace it?"

Approved save filegetSelectedFileexists() checkselectedFile.exists()Overwrite promptshowConfirmDialogNext stepnot shown in sourcefile existsuser answers
In what order do the existence check and the overwrite prompt happen, and what does the source show after the user answers?

Tracing a Save Dialog Step by Step

Worked example

A user saves a file that already exists

The program calls writeFile(). The user accepts the default name output.txt in the save dialog, and a file called output.txt is already in that folder. Trace what the program does up to the confirmation prompt.

  1. 1
    Create the dialog

    The null check finds that fileDialog is empty, so a new JFileChooser is created. Because fileDialog is an instance variable, it is stored on the object and not inside this one method call.

  2. 2
    Preselect the name

    setSelectedFile(new File("output.txt")) gives the dialog its default file name.

  3. 3
    Set the title

    setDialogTitle("Select File for Writing") labels the window.

  4. 4
    Show the save dialog

    showSaveDialog(this) opens the dialog. The program waits for the user to respond.

  5. 5
    Check the response

    The user approves, so the dialog does not return early. The code continues.

  6. 6
    Get the chosen file

    getSelectedFile() returns the File the user approved, named output.txt.

  7. 7
    Check for existence

    selectedFile.exists() returns true because the file is already present.

  8. 8
    Ask to replace

    JOptionPane.showConfirmDialog displays the message asking whether to replace the existing file.

Result

The program has reached the overwrite confirmation. The source does not show the code that runs after the user answers.

Mistakes Beginners Make With File Dialogs

  • Common mistake

    Using the open dialog to save a file

    What it looks like

    Calling showOpenDialog(this) in the code that writes a file

    Why it fails

    The source uses showOpenDialog(this) for reading and showSaveDialog(this) for writing. The method name is tied to the purpose of the dialog.

    Do this instead

    Use showSaveDialog(this) when the program is going to write a file.

  • Common mistake

    Continuing with file code after the dialog was canceled

    What it looks like

    Reading or writing a file immediately after showing the dialog, without checking the response

    Why it fails

    Both source methods check the return value and return early if the user canceled or closed the dialog.

    Do this instead

    Only run the file code after confirming that the user approved a file choice.

  • Common mistake

    Assuming the write dialog starts blank

    What it looks like

    Expecting the save dialog to have no name filled in

    Why it fails

    The source's writeFile() sets a default selected file named output.txt before showing the dialog.

    Do this instead

    Expect output.txt as the suggested name, and let the user change it if needed.

  • Common mistake

    Skipping the existence check before writing

    What it looks like

    Passing the chosen file straight to the write code

    Why it fails

    The source checks selectedFile.exists() and asks for confirmation before replacing an existing file.

    Do this instead

    Check exists() on the chosen file and ask the user before replacing it.

Practice Predicting the Dialog Path

EASY

A program's writeFile() method shows the save dialog. The user closes the dialog with the close button without choosing a file. Using the return value rule from this article, predict which code runs next and which code is skipped. Then explain why the existence check never runs in this case.

Hints
  • Both source methods return early when the user cancels or closes the dialog.
  • The existence check happens only after the approved file is retrieved with getSelectedFile().
MEDIUM

Write out, in order, the four setup steps that writeFile() performs before showing its dialog. Then state which property determines the default name the user sees.

Hints
  • Two of the steps set the dialog itself, and one step creates the dialog if it does not already exist.
  • The default name comes from the File object passed to setSelectedFile.

Key Takeaways

  • JFileChooser creates file dialogs so a user can choose a file for reading or writing instead of typing a path.
  • readFile() shows showOpenDialog(this) with the title Select File for Reading and no preselected file, while writeFile() shows showSaveDialog(this) with output.txt preselected and the title Select File for Writing.
  • Both methods check the dialog's return value and return early if the user canceled or closed the dialog, so the file code runs only after a real choice.
  • In writeFile(), selectedFile.exists() decides whether JOptionPane.showConfirmDialog asks the user to confirm replacing an existing file.