Using File Dialog Boxes
JFileChooser creates file dialogs that let a user choose a file for reading or writing instead of typing a path.
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
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.
| Feature | Reading (readFile) | Writing (writeFile) |
|---|---|---|
| Method that shows the dialog | showOpenDialog(this) | showSaveDialog(this) |
| Dialog title | Select File for Reading | Select File for Writing |
| Initially selected file | None (setSelectedFile(null)) | output.txt |
| Check on the return value | Returns early if canceled or closed | Returns 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?
Reveal 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.
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?"
Tracing a Save Dialog Step by Step
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.
- 1Create the dialog
The null check finds that
fileDialogis empty, so a newJFileChooseris created. BecausefileDialogis an instance variable, it is stored on the object and not inside this one method call. - 2Preselect the name
setSelectedFile(new File("output.txt"))gives the dialog its default file name. - 3Set the title
setDialogTitle("Select File for Writing")labels the window. - 4Show the save dialog
showSaveDialog(this)opens the dialog. The program waits for the user to respond. - 5Check the response
The user approves, so the dialog does not return early. The code continues.
- 6Get the chosen file
getSelectedFile()returns the File the user approved, namedoutput.txt. - 7Check for existence
selectedFile.exists()returns true because the file is already present. - 8Ask to replace
JOptionPane.showConfirmDialog displays the message asking whether to replace the existing file.
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 likeCalling showOpenDialog(this) in the code that writes a file
Why it failsThe source uses
showOpenDialog(this)for reading andshowSaveDialog(this)for writing. The method name is tied to the purpose of the dialog.Do this insteadUse 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 likeReading or writing a file immediately after showing the dialog, without checking the response
Why it failsBoth source methods check the return value and return early if the user canceled or closed the dialog.
Do this insteadOnly run the file code after confirming that the user approved a file choice.
Common mistake Assuming the write dialog starts blank
What it looks likeExpecting the save dialog to have no name filled in
Why it failsThe source's
writeFile()sets a default selected file namedoutput.txtbefore showing the dialog.Do this insteadExpect 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 likePassing the chosen file straight to the write code
Why it failsThe source checks
selectedFile.exists()and asks for confirmation before replacing an existing file.Do this insteadCheck exists() on the chosen file and ask the user before replacing it.
Practice Predicting the Dialog Path
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().
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
JFileChoosercreates file dialogs so a user can choose a file for reading or writing instead of typing a path.readFile()showsshowOpenDialog(this)with the title Select File for Reading and no preselected file, whilewriteFile()showsshowSaveDialog(this)withoutput.txtpreselected 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 whetherJOptionPane.showConfirmDialog asks the user to confirm replacing an existing file.