JFileChooser, File and FileFilter in java with Example using NetBeans

JFileChooser, File, and FileFilter in java

A very common use of a dialog box is to save and open files. Hardly any application can do without such a dialog. For this purpose, a ready-made dialog was made available in Java with the javax.swing.JFileChooser class. This offers a file explorer and buttons for opening, saving, and canceling. But you can also customize a ready-made dialog a little.

If you want to integrate the dialog directly into an application, an object of the JFileChooser class can be added to a container.


Example: how to use showOpenDialog in JFileChooser in java using NetBeans:

First, I create an object chooser of the class JFileChooser. A static method to open such a dialog directly, as in the JColorChooser class, does not exist here. Then I use the showOpenDialog method to display the dialog for opening files. Since the class only provides modal dialogs, the method expects a parent component as a parameter so that it can be blocked while the dialog is displayed. But since we don’t have a parent window in this simple example, we pass null. The screenshot below shows the dialog that appears when running the above source code.

jFileChooser

As you can see from the screenshot, the title of the dialog and the left button have the text “Open”. This is done by calling the showOpenDialog method. If you had called the showSaveDialog method instead, a “Save” button would appear instead.



Example: how to use showSaveDialog in JFileChooser in java using NetBeans:

Similar to the screenshot above, the screenshot for the save dialog looks like this:

jFileChooser

You can also determine the title of the dialog and the labeling of the left button yourself. That’s what the showDialog method is for. This method differs from the previously mentioned methods only in one additional parameter of type String. This is the text that should appear as the dialog title and label for the left button.

The corresponding screenshot then looks as follows. As you can see, now the title and text of the button have changed to ” Any operation ” compared to the screenshots above.

jFileChooser

In the examples, nothing would happen when you click “Save” or “Open” because you have to program the functionality of the buttons. We’ll now take the first example and extend it to include the name of the selected file.


Example: how to open a selected file in java using JFileChooser using NetBeans:

Since the dialog is modal, we get a value returned after pressing the “Open” or “Cancel” button. This value has either the value of the constant APPORVE_OPTION of the class JFileChooser for pressing the “Open” button or that of the constant CANCEL_OPTION for the “Cancel” button. With the following, if statement we check whether the “Open” button was clicked. If this has been clicked on, we output the selected file name. The JFileChooser provides the getSelectedFile method so that we can work with the selected file in our program. This returns an object of the File class.

jFileChooser

When clicked on the open button a message will be displayed in the output console “file open” as you can see in the below image:

jFileChooser

Now let’s add an example of how to embed an object of the JFileChooser class in its own frame. Let’s look at the following example:


Example: how to create JFileChooser dialog using JFrame in java using NetBeans:

As you can see, adding a JFileChooser object is just as easy as adding a JColorChooser object in the previous article. The following screenshot shows you our JFrame with our added  JFileChooser object.

jFileChooser

By default, when the constructor is called, the JFileChooser object is initialized as if it were a file chooser window for opening files. If you want to implement a save dialog, then before embedding it in the frame, you should specify the dialog type, ie whether it should be used for “save” or “open”. This can be controlled using the setDialogType method. The method looks like this:

This method has no return value and expects a dialog type that can be specified using the constants SAVE_DIALOG or OPEN_DIALOG of the JFileChooser class. An example call would be the following:


File in java

The java.io.File class in java is not only responsible for using files, but also for handling directories. They can be used to determine, for example, whether a file even exists. It offers additional methods to create directories or delete files.

The File class in java provides a total of four constructors I want to introduce you to, the two of them probably most frequently used constructors.

constructor description
File(String pathname) Creates a new object of class File with the passed pathname, this can be a path to a directory (e.g. c:/windows) or a file (e.g. c:/example.txt)
File(URI uri) Creates a new object of class File with the supplied URI. URI is short for Uniform Resource Identifier. The URI is also known, for example, as a so-called file URL. For example, a URI would look like this: file:///c/windows

As you may have noticed, slashes are used here for the paths instead of backslashes. we can use a slash in Java instead of two backslashes for path specifications, it makes sense to do this to save characters. Incidentally, this is also a common source of error for beginners.



Example: how to create a file on the hard disk using the File class in java using NetBeans:

First, I create a new object exampleFile of the File class with the path specification to a file named programmingdigest.txt. It should be noted that only the Java object is created here and not the file itself! It is then checked whether the path specified when creating the File object actually exists. If the path doesn’t exist, we go to the statement block of the if statement. The exists method returns true if the path exists and false if it doesn’t exist. By putting an exclamation mark in front of the existing method, I negate the result of the method to have the contents of the if statement executed if the path doesn’t exist.

Now execute the above source code, and you will see the programming digest.txt file will be created in the path which you specified in programming in my case I set the path C:/Users/Fawadkhan/Documents/programmingdigest.txt. You can see my file is created successfully

jFileChooser

jFileChooser



File Class Methods in java:

Here is a list of the most important methods of the File class in java:

method

description
boolean canExecute() Checks whether the java File object is executable for our application. If so, true is returned, otherwise false.
boolean canRead() Checks whether the File object is readable by our application. If so, true is returned, otherwise false.
boolean canWrite() Checks whether the java File object is writable for our application. If so, true is returned, otherwise false.
boolean createNewFile() Creates a new file with the name specified for the File object. Returns true after successful file creation.
boolean delete() Deletes a file or an empty directory. Returns true if deletion was successful.
boolean exists() Checks whether a directory or file exists. If so, true is returned, otherwise false.
String getAbsolutePath() Returns the absolute (complete) path to the file or directory.
String getName() Returns either the filename or the last directory of the absolute path.
String getParent() Returns the path of the parent directory as a string.
File getParentFile() Directly returns the parent directory as a File object.
boolean isAbsolute() Checks whether the path specification of the File object is absolute ( true ) or relative ( false ).
boolean isDirectory() Checks whether the path specification associated with the File object is a directory. If so, true is returned, otherwise false.
boolean isHidden() Checks if the File object is visible to our application. If so, true is returned, otherwise false.
long lastModified()

Returns the time when the file or directory was last modified. The return value long must then be converted into an actual date. This is done, for example, using the Date class, which as a constructor can accept a parameter of the long type.

Example: new Date(time).toString() returns the date as a string ( time is the variable to which the result of the lastModified method was assigned).

String[] list() Returns an array containing the paths of the files or directories contained in our directory associated with the File object in String form (similar to the dir command on the DOS command line).
File[] listFiles() Has the same functionality as the list method, but returns an array of File objects.
static File[] listRoots() Similar to listFiles, but the system directories are returned here, e.g. hard-disk C, DVD drive D, etc.
boolean mkdir() Creates a new directory with the name specified for the File object. Returns true after a successful directory creation.
boolean mkdirs() Creates all directories necessary to realize the full path of the File object. Returns true after successfully creating the directories.
boolean renameTo(File dest) Changes the name of the file or directory of the current File object to the name of the passed File object.
boolean setExecutable(boolean executable,boolean ownerOnly) Sets the file of our File object to “executable”. The first parameter regulates whether the file is generally executable. The second parameter can be used to specify that the file can only be run by the owner.

boolean setReadable(boolean readable,boolean ownerOnly)

Sets the file or directory of our File object to “readable”. The first parameter regulates whether the file is generally readable. The second parameter can be used to specify that the file can only be read by the owner.
boolean setReadOnly()

Sets the write protection of a file or a directory of our File object.

boolean setWriteable(boolean writeable, boolean ownerOnly) Sets the file/directory of our File object to “writable”. The first parameter regulates whether the file is generally writable. The second parameter can be used to specify that the file can only be written to by the owner.
String to String() Returns the path specification associated with the File object, this can also be a relative path.
URI toURI() Converts the path specification into a URI address.


FileFilter in java

In order to use our JFileChooser more efficiently, we can use a FileFilter class in java. This allows us, for example, to limit the selection of files to specific extensions such as .txt.

In Java Version 1.5 you had to create such a FileFilter yourself using the abstract class or the java.io.FileFilter interface. As of Java Version 1.6, there is a ready-made class FileNameExtensionFilter that we only have to adapt to our purposes.

The FileNameExtensionFilter class is very easy to use. Let’s take a look at the creation of such an object:

Since the FileNameExtensionFilter class is derived from the FileFilter class in java, we can use objects of this class as a FileFilter. The constructor expects at least two parameters. The first parameter is the description of the filter. This is followed by all endings that are to be included with this filter.


Example: how to use FileFilter for image files into our JFileChooser in java using NetBeans:

In the above example, we first create an object of the FileNameExtensionFilter class with the description “Images” and the desired file extensions. The FileChooser opens in the specified folder and only shows the files that have the specified file extensions. Folders are not affected by this filter and are always displayed. After we have created our FileChooser, we add our previously created FileFilter using the addChoosableFileFilter method. You already know the rest of the Java source code.


After running the above Java source code, you will get the All files as you can see in the following picture:

jFileChooser

When you change the file type from all files to images you will see only images file as you can see in the following picture:

jFileChooser

In this way, multiple FileFilters can be used in Java. For example, a different file filter can be used for an “Open” dialog than in the “Save” dialog. However, several different FileFilters can also be defined for a JFileChooser object.

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: