Using Jfilechooser to Read a File in Java

File choosers provide a GUI for navigating the file organisation, and then either choosing a file or directory from a list, or entering the name of a file or directory. To display a file chooser, yous usually utilize the JFileChooser API to show a modal dialog containing the file chooser. Some other way to present a file chooser is to add together an instance of JFileChooser to a container.


Note:

If yous intend to distribute your program as a sandbox Coffee Web Start application, then instead of using the JFileChooser API you should employ the file services provided by the JNLP API. These services — FileOpenService and FileSaveService — not only provide support for choosing files in a restricted environment, just also accept intendance of actually opening and saving them. An example of using these services is in JWSFileChooserDemo. Documentation for using the JNLP API tin be found in the Coffee Web Start lesson.


Click the Launch push to run JWSFileChooserDemo using Java™ Web Kickoff (download JDK vii or subsequently). Alternatively, to compile and run the instance yourself, consult the example index.

Launches the JWSFileChooserDemo application

When working with the JWSFileChooserDemo example, exist careful not to lose files that you need. Whenever you click the save push and select an existing file, this demo brings up the File Exists dialog box with a request to replace the file. Accepting the request overwrites the file.

The balance of this department discusses how to use the JFileChooser API. A JFileChooser object but presents the GUI for choosing files. Your program is responsible for doing something with the chosen file, such as opening or saving it. Refer to Bones I/O for information on how to read and write files.

The JFileChooser API makes information technology easy to bring up open and salvage dialogs. The type of look and feel determines what these standard dialogs wait like and how they differ. In the Java look and feel, the save dialog looks the same as the open dialog, except for the title on the dialog's window and the text on the button that approves the functioning. Hither is a picture of a standard open dialog in the Java look and experience:

A standard open dialog shown in the Java look and feel

Here is a movie of an application chosen FileChooserDemo that brings up an open dialog and a salvage dialog.

A program that brings up an open or save dialog

Attempt this:

  1. Compile and run the example, consult the example index.
  2. Click the Open a File button. Navigate around the file chooser, choose a file, and click the dialog's Open push.
  3. Use the Salvage a File button to bring upwards a salvage dialog. Try to employ all of the controls on the file chooser.
  4. In the source file FileChooserDemo.java, modify the file selection mode to directories-only fashion. (Search for DIRECTORIES_ONLY and uncomment the line that contains information technology.) Then compile and run the example over again. Yous will only exist able to see and select directories, not ordinary files.

Bringing up a standard open dialog requires only ii lines of code:

//Create a file chooser final JFileChooser fc = new JFileChooser(); ...            //In response to a button click:            int returnVal = fc.showOpenDialog(aComponent);          

The argument to the showOpenDialog method specifies the parent component for the dialog. The parent component affects the position of the dialog and the frame that the dialog depends on. For example, the Java wait and feel places the dialog direct over the parent component. If the parent component is in a frame, then the dialog is dependent on that frame. This dialog disappears when the frame is minimized and reappears when the frame is maximized.

By default, a file chooser that has not been shown earlier displays all files in the user's home directory. You tin can specify the file chooser's initial directory by using ane of JFileChooser's other constructors, or you lot can set the directory with the setCurrentDirectory method.

The call to showOpenDialog appears in the actionPerformed method of the Open up a File button'southward action listener:

public void actionPerformed(ActionEvent e) {     //Handle open push activeness.     if (e.getSource() == openButton) {         int returnVal = fc.showOpenDialog(FileChooserDemo.this);          if (returnVal == JFileChooser.APPROVE_OPTION) {             File file = fc.getSelectedFile();             //This is where a real application would open the file.             log.suspend("Opening: " + file.getName() + "." + newline);         } else {             log.append("Open control cancelled past user." + newline);         }    } ... }          

The evidenceXxxDialog methods render an integer that indicates whether the user selected a file. Depending on how yous use a file chooser, it is often sufficient to cheque whether the return value is APPROVE_OPTION and then not to change any other value. To go the called file (or directory, if yous prepare the file chooser to allow directory selections), telephone call the getSelectedFile method on the file chooser. This method returns an example of File.

The case obtains the name of the file and uses information technology in the log bulletin. You can call other methods on the File object, such as getPath, isDirectory, or exists to obtain information about the file. You can also call other methods such as delete and rename to change the file in some way. Of course, you lot might also want to open or salvage the file past using 1 of the reader or writer classes provided by the Coffee platform. See Basic I/O for information about using readers and writers to read and write data to the file organization.

The instance plan uses the aforementioned example of the JFileChooser class to brandish a standard relieve dialog. This time the program calls showSaveDialog:

int returnVal = fc.showSaveDialog(FileChooserDemo.this);          

By using the same file chooser instance to display its open and save dialogs, the program reaps the following benefits:

  • The chooser remembers the current directory betwixt uses, so the open and salvage versions automatically share the same current directory.
  • You have to customize only one file chooser, and the customizations employ to both the open and save versions.

Finally, the example program has commented-out lines of code that permit y'all change the file selection mode. For case, the following line of code makes the file chooser able to select only directories, and non files:

fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);          

Another possible selection manner is FILES_AND_DIRECTORIES. The default is FILES_ONLY. The following picture shows an open up dialog with the file choice mode set to DIRECTORIES_ONLY. Annotation that, in the Java wait and feel at to the lowest degree, merely directories are visible — not files.

A file chooser in DIRECTORIES_ONLY mode

If you want to create a file chooser for a task other than opening or saving, or if y'all want to customize the file chooser, keep reading. We will hash out the post-obit topics:

  • Another Example: FileChooserDemo2
  • Using a File Chooser for a Custom Job
  • Filtering the Listing of Files
  • Customizing the File View
  • Providing an Accompaniment Component
  • The File Chooser API
  • Examples that Use File Choosers

Some other Instance: FileChooserDemo2

Allow us look at FileChooserDemo2 example, a modified version of the previous demo program that uses more than of the JFileChooser API. This example uses a file chooser that has been customized in several ways. Similar the original example, the user invokes a file chooser with the push of a button. Here is a picture of the file chooser:

A file chooser with various customizations

As the figure shows, this file chooser has been customized for a special chore (Attach), provides a user-choosable file filter (Merely Images), uses a special file view for image files, and has an accompaniment component that displays a thumbnail sketch of the currently selected image file.

The remainder of this section shows you the lawmaking that creates and customizes this file chooser. Run into the example index for links to all the files required past this example.

Using a File Chooser for a Custom Chore

As you lot have seen, the JFileChooser course provides the showOpenDialog method for displaying an open dialog and the showSaveDialog method for displaying a save dialog.

The class has another method, showDialog, for displaying a file chooser for a custom task in a dialog. In the Java look and experience, the only departure betwixt this dialog and the other file chooser dialogs is the title on the dialog window and the label on the approve button. Hither is the code from FileChooserDemo2 that brings upwardly the file chooser dialog for the Attach task:

JFileChooser fc = new JFileChooser(); int returnVal = fc.showDialog(FileChooserDemo2.this, "Attach");          

The get-go argument to the showDialog method is the parent component for the dialog. The second argument is a Cord object that provides both the title for the dialog window and the label for the approve button.

In one case once again, the file chooser doesn't practise anything with the selected file. The programme is responsible for implementing the custom chore for which the file chooser was created.

Filtering the List of Files

By default, a file chooser displays all of the files and directories that it detects, except for hidden files. A plan can utilise one or more than file filters to a file chooser so that the chooser shows only some files. The file chooser calls the filter's accept method for each file to decide whether it should be displayed. A file filter accepts or rejects a file based on criteria such as file type, size, ownership, and so on. Filters touch on the list of files displayed by the file chooser. The user can enter the name of whatsoever file even if information technology is not displayed.

JFileChooser supports iii dissimilar kinds of filtering. The filters are checked in the order listed here. For case, an application-controlled filter sees just those files accepted by the congenital-in filtering.

Built-in filtering
Filtering is set up through specific method calls on a file chooser. Currently the but congenital-in filter available is for hidden files, such as those whose names begin with period (.) on UNIX systems. By default, hidden files are not shown. Call setFileHidingEnabled(false) to show hidden files.
Awarding-controlled filtering
The awarding determines which files are shown. Create a custom subclass of FileFilter, instantiate information technology, and apply the instance as an argument to the setFileFilter method. The installed filter is displayed on the list of user-choosable filters. The file chooser shows only those files that the filter accepts.
User-choosable filtering
The file chooser GUI provides a list of filters that the user can choose from. When the user chooses a filter, the file chooser shows only those files accepted past that filter. FileChooserDemo2 adds a custom file filter to the listing of user-choosable filters:
fc.addChoosableFileFilter(new ImageFilter());              
By default, the list of user-choosable filters includes the Have All filter, which enables the user to encounter all non-hidden files. This example uses the following code to disable the Accept All filter:
fc.setAcceptAllFileFilterUsed(false);              
Our custom file filter is implemented in ImageFilter.coffee and is a subclass of FileFilter. The ImageFilter class implements the getDescription method to return "Just Images" — a string to put in the list of user-choosable filters. ImageFilter also implements the accept method so that information technology accepts all directories and any file that has a .png, .jpg, .jpeg, .gif, .tif, or .tiff filename extension.
public boolean accept(File f) {                if (f.isDirectory()) {         return true;     }                Cord extension = Utils.getExtension(f);     if (extension != null) {         if (extension.equals(Utils.tiff) ||             extension.equals(Utils.tif) ||             extension.equals(Utils.gif) ||             extension.equals(Utils.jpeg) ||             extension.equals(Utils.jpg) ||             extension.equals(Utils.png)) {                 render true;         } else {             render false;         }     }      return false; }              
By accepting all directories, this filter allows the user to navigate effectually the file system. If the bold lines were omitted from this method, the user would be express to the directory with which the chooser was initialized.

The preceding code sample uses the getExtension method and several string constants from Utils.java, shown here:

public class Utils {      public final static String jpeg = "jpeg";     public concluding static Cord jpg = "jpg";     public concluding static Cord gif = "gif";     public final static String tiff = "tiff";     public concluding static Cord tif = "tif";     public final static String png = "png";      /*      * Get the extension of a file.      */       public static Cord getExtension(File f) {         String ext = null;         String s = f.getName();         int i = due south.lastIndexOf('.');          if (i > 0 &&  i < s.length() - 1) {             ext = southward.substring(i+1).toLowerCase();         }         return ext;     } }              

Customizing the File View

In the Java look and feel, the chooser's list shows each file's proper noun and displays a modest icon that represents whether the file is a true file or a directory. You can customize this file view by creating a custom subclass of FileView and using an instance of the grade as an statement to the setFileView method. The example uses an instance of a custom course, implemented in ImageFileView.coffee, as the file chooser'due south file view.

fc.setFileView(new ImageFileView());          

The ImageFileView course shows a dissimilar icon for each type of paradigm accepted by the image filter described previously.

The ImageFileView course overrides the v abstract methods defined in the FileView equally follows.

String getTypeDescription(File f)
Returns a description of the file type. Here is ImageFileView's implementation of this method:
public Cord getTypeDescription(File f) {     String extension = Utils.getExtension(f);     String type = zippo;      if (extension != null) {         if (extension.equals(Utils.jpeg) ||             extension.equals(Utils.jpg)) {             blazon = "JPEG Image";         } else if (extension.equals(Utils.gif)){             type = "GIF Image";         } else if (extension.equals(Utils.tiff) ||                    extension.equals(Utils.tif)) {             type = "TIFF Prototype";         } else if (extension.equals(Utils.png)){             type = "PNG Epitome";         }     }     return blazon; }              
Icon getIcon(File f)
Returns an icon representing the file or its blazon. Here is ImageFileView's implementation of this method:
public Icon getIcon(File f) {     String extension = Utils.getExtension(f);     Icon icon = null;      if (extension != null) {         if (extension.equals(Utils.jpeg) ||             extension.equals(Utils.jpg)) {             icon = jpgIcon;         } else if (extension.equals(Utils.gif)) {             icon = gifIcon;         } else if (extension.equals(Utils.tiff) ||                    extension.equals(Utils.tif)) {             icon = tiffIcon;         } else if (extension.equals(Utils.png)) {             icon = pngIcon;         }     }     return icon; }              
String getName(File f)
Returns the name of the file. Most implementations of this method should return null to indicate that the look and feel should figure it out. Another common implementation returns f.getName().
String getDescription(File f)
Returns a description of the file. The intent is to describe individual files more specifically. A common implementation of this method returns nil to indicate that the wait and feel should figure it out.
Boolean isTraversable(File f)
Returns whether a directory is traversable. Most implementations of this method should return cypher to indicate that the look and feel should effigy information technology out. Some applications might want to prevent users from descending into a sure type of directory because it represents a compound document. The isTraversable method should never return truthful for a non-directory.

Providing an Accompaniment Component

The customized file chooser in FileChooserDemo2 has an accessory component. If the currently selected item is a PNG, JPEG, TIFF, or GIF image, the accessory component displays a thumbnail sketch of the image. Otherwise, the accessory component is empty. Bated from a previewer, probably the most mutual use for the accessory component is a panel with more controls on it such as check boxes that toggle between features.

The instance calls the setAccessory method to establish an example of the ImagePreview grade, implemented in ImagePreview.java, as the chooser'due south accessory component:

fc.setAccessory(new ImagePreview(fc));          

Any object that inherits from the JComponent class tin be an accessory component. The component should have a preferred size that looks good in the file chooser.

The file chooser fires a property change result when the user selects an detail in the list. A plan with an accompaniment component must register to receive these events to update the accessory component whenever the selection changes. In the example, the ImagePreview object itself registers for these events. This keeps all the code related to the accompaniment component together in one grade.

Hither is the instance's implementation of the propertyChange method, which is the method chosen when a property change issue is fired:

//where member variables are declared            File file = null; ... public void propertyChange(PropertyChangeEvent east) {     boolean update = false;     Cord prop = e.getPropertyName();      //If the directory inverse, don't show an epitome.     if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {         file = null;         update = true;      //If a file became selected, notice out which one.     } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {         file = (File) e.getNewValue();         update = true;     }      //Update the preview accordingly.     if (update) {         thumbnail = null;         if (isShowing()) {             loadImage();             repaint();         }     } }          

If SELECTED_FILE_CHANGED_PROPERTY is the property that changed, this method obtains a File object from the file chooser. The loadImage and repaint methods utilize the File object to load the prototype and repaint the accompaniment component.

The File Chooser API

The API for using file choosers falls into these categories:

  • Creating and Showing the File Chooser
  • Selecting Files and Directories
  • Navigating the File Chooser'due south List
  • Customizing the File Chooser
Creating and Showing the File Chooser
Method or Constructor Purpose
JFileChooser()
JFileChooser(File)
JFileChooser(String)
Creates a file chooser instance. The File and String arguments, when present, provide the initial directory.
int showOpenDialog(Component)
int showSaveDialog(Component)
int showDialog(Component, String)
Shows a modal dialog containing the file chooser. These methods render APPROVE_OPTION if the user canonical the performance and CANCEL_OPTION if the user cancelled it. Some other possible return value is ERROR_OPTION, which means an unanticipated error occurred.
Selecting Files and Directories
Method Purpose
void setSelectedFile(File)
File getSelectedFile()
Sets or obtains the currently selected file or (if directory option has been enabled) directory.
void setSelectedFiles(File[])
File[] getSelectedFiles()
Sets or obtains the currently selected files if the file chooser is set to allow multiple selection.
void setFileSelectionMode(int)
void getFileSelectionMode()
boolean isDirectorySelectionEnabled()
boolean isFileSelectionEnabled()
Sets or obtains the file selection way. Acceptable values are FILES_ONLY (the default), DIRECTORIES_ONLY, and FILES_AND_DIRECTORIES.
Interprets whether directories or files are selectable co-ordinate to the electric current pick mode.
void setMultiSelectionEnabled(boolean)
boolean isMultiSelectionEnabled()
Sets or interprets whether multiple files tin be selected at once. By default, a user can choose just one file.
void setAcceptAllFileFilterUsed(boolean)
boolean isAcceptAllFileFilterUsed()
Sets or obtains whether the AcceptAll file filter is used as an allowable choice in the choosable filter list; the default value is true.
Dialog createDialog(Component) Given a parent component, creates and returns a new dialog that contains this file chooser, is dependent on the parent'southward frame, and is centered over the parent.
Navigating the File Chooser's List
Method Purpose
void ensureFileIsVisible(File) Scrolls the file chooser'southward list such that the indicated file is visible.
void setCurrentDirectory(File)
File getCurrentDirectory()
Sets or obtains the directory whose files are displayed in the file chooser's list.
void changeToParentDirectory() Changes the list to display the current directory'due south parent.
void rescanCurrentDirectory() Checks the file system and updates the chooser's list.
void setDragEnabled(boolean)
boolean getDragEnabled()
Sets or obtains the property that determines whether automatic drag handling is enabled. See Drag and Drop and Information Transfer for more details.
Customizing the File Chooser
Method Purpose
void setAccessory(javax.swing.JComponent)
JComponent getAccessory()
Sets or obtains the file chooser's accessory component.
void setFileFilter(FileFilter)
FileFilter getFileFilter()
Sets or obtains the file chooser'south primary file filter.
void setFileView(FileView)
FileView getFileView()
Sets or obtains the chooser's file view.
FileFilter[] getChoosableFileFilters()
void addChoosableFileFilter(FileFilter)
boolean removeChoosableFileFilter(FileFilter)
void resetChoosableFileFilters()
FileFilter getAcceptAllFileFilter()
Sets, obtains, or modifies the list of user-choosable file filters.
void setFileHidingEnabled(boolean)
boolean isFileHidingEnabled()
Sets or obtains whether subconscious files are displayed.
void setControlButtonsAreShown(boolean)
boolean getControlButtonsAreShown()
Sets or obtains the belongings that indicates whether the Corroborate and Cancel buttons are shown in the file chooser. This holding is true by default.

Examples That Apply File Choosers

This tabular array shows the examples that use file choosers and points to where those examples are described.

Example Where Described Notes
FileChooserDemo This section Displays an open dialog and a save dialog.
FileChooserDemo2 This department Uses a file chooser with custom filtering, a custom file view, and an accessory component.
JWSFileChooserDemo This department Uses the JNLP API to open and save files.

foleyweesamight.blogspot.com

Source: https://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

0 Response to "Using Jfilechooser to Read a File in Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel