Which FileChooser method returns the file the user selected?

A JFileChooser lets the user select a file from the file system.

We can create an object of the JFileChooser class. It allows the user to choose only files, only directories, or both.

Use one of the three non-static methods, showOpenDialog(), showSaveDialog(), or showDialog(), to display it in a JDialog.

We can check for the return value, which is an int, from the method we called to show the dialog.

If it returns JFileChooser.APPROVE_OPTION, the user made a selection. JFileChooser.CANCEL_OPTION and JFileChooser.ERROR_OPTION indicate that either user cancelled the dialog box or some kind of error occurred.

To get the selected file, call the getSelectedFile() or getSelectedFiles() method, which returns a File object and a File array, respectively.

We can reuse the file chooser object. It remembers the last visited folder.

By default, a JFileChooser starts displaying files from the user's default directory.

We can specify the initial directory in its constructor or using its setCurrentDirectory() method.

The following codecCreates a file chooser with the default initial directory

JFileChooser fileChooser = new JFileChooser();

The following code creates a file chooser, with an initial directory of C:\myjava.

JFileChooser fileChooser = new JFileChooser("C:\\myjava");

By default, a file chooser can only select files.

To select files and directories

fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

To allow multiple selection

fileChooser.setMultiSelectionEnabled(true);

The following code shows how to display an open file chooser dialog box and check if the user selected a file. If the user makes a selection, print the file path on the standard output.

// Display an open file chooser int returnValue = fileChooser.showOpenDialog(null); import java.io.File; //from w w w .j a va 2 s.co m import javax.swing.JFileChooser; public class Main { public static void main(String[] args) { // Display an open file chooser JFileChooser fileChooser = new JFileChooser(); int returnValue = fileChooser.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); System.out.println("we selected: " + selectedFile); } } }

We can customize the dialog box title and the approve button text before displaying it as follows.

To change the dialog's title

fileChooser.setDialogTitle("Open a picture file");

To change the button's text

fileChooser.setApproveButtonText("Open File");

To open a file chooser with Attach as its title and approve button's text

int returnValue = fileChooser.showDialog(null, "Attach"); if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); System.out.println("Attaching file: " + selectedFile); }

Setting the approve button's text does not change the return value of the method.

File Filter

A JFileChooser can use a file filter which is a set of criteria that it applies before it shows a file in the dialog box.

A file filter is an object of the FileFilter class, which is in the javax.swing.filechooser package.

The FileFilter class is an abstract class. We need to override the accept() and getDescription() methods.

The accept() method is called with a file reference when the file chooser wants to show a file. If the accept() method returns true, the file is shown. Otherwise, the file is not shown.

The following code creates and sets a file filter to only show either a directory or a file with a doc extension.

import java.io.File; //from ww w. ja v a 2 s .com import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; public class Main { public static void main(String[] args) { // Create a file filter to show only a directory or .doc files FileFilter filter = new FileFilter() { @Override public boolean accept(File f) { if (f.isDirectory()) { return true; } String fileName = f.getName().toLowerCase(); if (fileName.endsWith(".doc")) { return true; } return false; // Reject any other files } @Override public String getDescription() { return "Word Document"; } }; // Set the file filter JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileFilter(filter); int returnValue = fileChooser.showDialog(null, "Attach"); if (returnValue == JFileChooser.APPROVE_OPTION) { // Process the file } } }

File Name Extension Filter

We can use the FileNameExtensionFilter class which inherits from the FileFilter class to filer files by file extension.

Its constructor accepts the file extensions and its description. The second argument is a variable length argument.

After we create an object of the FileNameExtensionFilter class, we need to call the addChoosableFileFilter() method of the file chooser to set a filter.

The following code adds "java" and "jav" as file name extension filters.

import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; /*from w w w.j av a2 s.c om*/ public class Main { public static void main(String[] args) { FileNameExtensionFilter extFilter = new FileNameExtensionFilter( "Java Source File", "java", "jav"); // Set the file filter JFileChooser fileChooser = new JFileChooser(); fileChooser.addChoosableFileFilter(extFilter); int returnValue = fileChooser.showDialog(null, "Attach"); if (returnValue == JFileChooser.APPROVE_OPTION) { // Process the file } } }

To Disable "accept all files filter"

fileChooser.setAcceptAllFileFilterUsed(false);

To check if "accept all files filter" is enabled, use the isAcceptAllFileFilterUsed() method, which returns true if a file chooser is using this filter.

To get the reference of "accept all files filter" using the getAcceptAllFileFilter() method.

The following code sets the "accept all files filter" if it is not already set.

if (!fileChooser.isAcceptAllFileFilterUsed()) { fileChooser.setAcceptAllFileFilterUsed(true); }

To get the associated icon for a file type, use the file chooser's getIcon(java.io.File file) method, which returns an Icon object. note that we can display an Icon object using a JLabel component.

Creates a dialog box to choose a file or directory to load or save. More...

 FileChooser (const String &dialogBoxTitle, const File &initialFileOrDirectory=File(), const String &filePatternsAllowed=String(), bool useOSNativeDialogBox=true, bool treatFilePackagesAsDirectories=false, Component *parentComponent=nullptr)
 Creates a FileChooser. More...
 
 ~FileChooser ()
 Destructor. More...
 
bool browseForFileToOpen (FilePreviewComponent *previewComponent=nullptr)
 Shows a dialog box to choose a file to open. More...
 
bool browseForMultipleFilesToOpen (FilePreviewComponent *previewComponent=nullptr)
 Same as browseForFileToOpen, but allows the user to select multiple files. More...
 
bool browseForFileToSave (bool warnAboutOverwritingExistingFiles)
 Shows a dialog box to choose a file to save. More...
 
bool browseForDirectory ()
 Shows a dialog box to choose a directory. More...
 
bool browseForMultipleFilesOrDirectories (FilePreviewComponent *previewComponent=nullptr)
 Same as browseForFileToOpen, but allows the user to select multiple files and directories. More...
 
bool showDialog (int flags, FilePreviewComponent *previewComponent)
 Runs a dialog box for the given set of option flags. More...
 
void launchAsync (int flags, std::function< void(const FileChooser &)>, FilePreviewComponent *previewComponent=nullptr)
 Use this method to launch the file browser window asynchronously. More...
 
File getResult () const
 Returns the last file that was chosen by one of the browseFor methods. More...
 
Array< File > getResults () const noexcept
 Returns a list of all the files that were chosen during the last call to a browse method. More...
 
URL getURLResult () const
 Returns the last document that was chosen by one of the browseFor methods. More...
 
const Array< URL > & getURLResults () const noexcept
 Returns a list of all the files that were chosen during the last call to a browse method. More...
 

Creates a dialog box to choose a file or directory to load or save.

◆ FileChooser()

FileChooser::FileChooser ( const String &  dialogBoxTitle,
const File &  initialFileOrDirectory = File(),
const String &  filePatternsAllowed = String(),
bool  useOSNativeDialogBox = true,
bool  treatFilePackagesAsDirectories = false,
Component *  parentComponent = nullptr 
)

Creates a FileChooser.

After creating one of these, use one of the browseFor... methods to display it.

Parameters
dialogBoxTitlea text string to display in the dialog box to tell the user what's going on
initialFileOrDirectorythe file or directory that should be selected when the dialog box opens. If this parameter is set to File(), a sensible default directory will be used instead. When using native dialogs, not all platforms will actually select the file. For example, on macOS, when initialFileOrDirectory is a file, only the parent directory of initialFileOrDirectory will be used as the initial directory of the native file chooser.

Note: On iOS when saving a file, a user will not be able to change a file name, so it may be a good idea to include at least a valid file name in initialFileOrDirectory. When no filename is found, "Untitled" will be used.

Also, if you pass an already existing file on iOS, that file will be automatically copied to the destination chosen by user and if it can be previewed, its preview will be presented in the dialog too. You will still be able to write into this file copy, since its URL will be returned by getURLResult(). This can be useful when you want to save e.g. an image, so that you can pass a (temporary) file with low quality preview and after the user picks the destination, you can write a high quality image into the copied file. If you create such a temporary file, you need to delete it yourself, once it is not needed anymore.

Parameters
filePatternsAlloweda set of file patterns to specify which files can be selected - each pattern should be separated by a comma or semi-colon, e.g. "*" or "*.jpg;*.gif". The native MacOS file browser only supports wildcard that specify extensions, so "*.jpg" is OK but "myfilename*" will not work. An empty string means that all files are allowed
useOSNativeDialogBoxif true, then a native dialog box will be used if possible; if false, then a Juce-based browser dialog box will always be used
treatFilePackagesAsDirectoriesif true, then the file chooser will allow the selection of files inside packages when invoked on OS X and when using native dialog boxes.
parentComponentAn optional component which should be the parent for the file chooser. If this is a nullptr then the FileChooser will be a top-level window. AUv3s on iOS must specify this parameter as opening a top-level window in an AUv3 is forbidden due to sandbox restrictions.
See alsobrowseForFileToOpen, browseForFileToSave, browseForDirectory

◆ ~FileChooser()

FileChooser::~FileChooser ( )

◆ browseForFileToOpen()

Shows a dialog box to choose a file to open.

This will display the dialog box modally, using an "open file" mode, so that it won't allow non-existent files or directories to be chosen.

Parameters
previewComponentan optional component to display inside the dialog box to show special info about the files that the user is browsing. The component will not be deleted by this object, so the caller must take care of it.
Returnstrue if the user selected a file, in which case, use the getResult() method to find out what it was. Returns false if they cancelled instead. See alsobrowseForFileToSave, browseForDirectory

◆ browseForMultipleFilesToOpen()

Same as browseForFileToOpen, but allows the user to select multiple files.

The files that are returned can be obtained by calling getResults(). See browseForFileToOpen() for more info about the behaviour of this method.

◆ browseForFileToSave()

bool FileChooser::browseForFileToSave ( bool  warnAboutOverwritingExistingFiles)

Shows a dialog box to choose a file to save.

This will display the dialog box modally, using an "save file" mode, so it will allow non-existent files to be chosen, but not directories.

Parameters
warnAboutOverwritingExistingFilesif true, the dialog box will ask the user if they're sure they want to overwrite a file that already exists
Returnstrue if the user chose a file and pressed 'ok', in which case, use the getResult() method to find out what the file was. Returns false if they cancelled instead. See alsobrowseForFileToOpen, browseForDirectory

◆ browseForDirectory()

bool FileChooser::browseForDirectory ( )

Shows a dialog box to choose a directory.

This will display the dialog box modally, using an "open directory" mode, so it will only allow directories to be returned, not files.

Returnstrue if the user chose a directory and pressed 'ok', in which case, use the getResult() method to find out what they chose. Returns false if they cancelled instead. See alsobrowseForFileToOpen, browseForFileToSave

◆ browseForMultipleFilesOrDirectories()

bool FileChooser::browseForMultipleFilesOrDirectories ( FilePreviewComponent *  previewComponent = nullptr)

Same as browseForFileToOpen, but allows the user to select multiple files and directories.

The files that are returned can be obtained by calling getResults(). See browseForFileToOpen() for more info about the behaviour of this method.

◆ showDialog()

◆ launchAsync()

Use this method to launch the file browser window asynchronously.

This will create a file browser dialog based on the settings in this structure and will launch it modally, returning immediately.

You must specify a callback which is called when the file browser is cancelled or a file is selected. To abort the file selection, simply delete the FileChooser object.

You must ensure that the lifetime of the callback object is longer than the lifetime of the file-chooser.

◆ getResult()

◆ getResults()

Array<File> FileChooser::getResults ( ) const
noexcept

Returns a list of all the files that were chosen during the last call to a browse method.

On mobile platforms, the file browser may return a URL instead of a local file. Therefore, on mobile platforms, you should call getURLResults() instead.

This array may be empty if no files were chosen, or can contain multiple entries if multiple files were chosen.

See alsogetURLResults, getResult

◆ getURLResult()

URL FileChooser::getURLResult ( ) const

Returns the last document that was chosen by one of the browseFor methods.

Use this method if you are using the FileChooser on a mobile platform which may return a URL to a remote document. If a local file is chosen then you can convert this file to a JUCE File class via the URL::getLocalFile method.

Note: On iOS you must use the returned URL object directly (you are also allowed to copy- or move-construct another URL from the returned URL), rather than just storing the path as a String and then creating a new URL from that String. This is because the returned URL contains internally a security bookmark that is required to access the files pointed by it. Then, once you stop dealing with the file pointed by the URL, you should dispose that URL object, so that the security bookmark can be released by the system (only a limited number of such URLs is allowed).

See alsogetResult, URL::getLocalFile

◆ getURLResults()

const Array<URL>& FileChooser::getURLResults ( ) const
noexcept

Returns a list of all the files that were chosen during the last call to a browse method.

Use this method if you are using the FileChooser on a mobile platform which may return a URL to a remote document. If a local file is chosen then you can convert this file to a JUCE File class via the URL::getLocalFile method.

This array may be empty if no files were chosen, or can contain multiple entries if multiple files were chosen.

Note: On iOS you must use the returned URL object directly (you are also allowed to copy- or move-construct another URL from the returned URL), rather than just storing the path as a String and then creating a new URL from that String. This is because the returned URL contains internally a security bookmark that is required to access the files pointed by it. Then, once you stop dealing with the file pointed by the URL, you should dispose that URL object, so that the security bookmark can be released by the system (only a limited number of such URLs is allowed).

See alsogetResults, URL::getLocalFile

◆ isPlatformDialogAvailable()

static bool FileChooser::isPlatformDialogAvailable ( )
static

Returns if a native filechooser is currently available on this platform.

Note: On iOS this will only return true if you have iCloud permissions and code-signing enabled in the Projucer and have added iCloud containers to your app in Apple's online developer portal. Additionally, the user must have installed the iCloud app on their device and used the app at least once.

◆ registerCustomMimeTypeForFileExtension()

static void FileChooser::registerCustomMimeTypeForFileExtension ( const String &  mimeType,
const String &  fileExtension 
)
static

Associate a particular file-extension to a mime-type.

On Android, JUCE needs to convert common file extensions to mime-types when using wildcard filters in native file chooser dialog boxes. JUCE has an extensive conversion table to convert between the most common file-types and mime-types transparently, but some more obscure file-types may be missing. Use this method to register your own mime-type to file extension conversions. Please contact the JUCE team if you think that a common mime-type/file-extension entry is missing in JUCE's internal tables. Does nothing on other platforms.

The documentation for this class was generated from the following file: