Java JFileChooser getFilePath()

Here you can find the source of getFilePath()

Description

This method shows a dialog where a file can be selected and returns the file's path afterwards.

License

Open Source License

Return

absolute path of a selected file

Declaration

public static String getFilePath() 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.awt.HeadlessException;
import java.io.*;

import javax.swing.JFileChooser;

public class Main {
    /**//from  w w  w  .j  a  v  a  2s. c  o  m
     * this variable sets the title of the dialog shown after calling
     * getFilePath()
     */
    private static final String FILEDIALOG_TITLE = "Select filename";

    /**
     * This method shows a dialog where a file can be selected and returns the
     * file's path afterwards.
     *
     * @return absolute path of a selected file
     */
    public static String getFilePath() {
        String filePath = "";

        try {
            final JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.setDialogTitle(FILEDIALOG_TITLE);
            int returnVal = fileChooser.showOpenDialog(null);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File chosenFile = fileChooser.getSelectedFile();
                filePath = chosenFile.getAbsolutePath();
            }
        } catch (HeadlessException hlEx) {
            System.err.println("headless error: " + hlEx.getMessage());
        } catch (SecurityException secEx) {
            System.err.println("security error: " + secEx.getMessage());
        }

        return filePath;
    }
}

Related

  1. getFileChooserSelectedFile(JFileChooser fchooser, boolean directoryOnly, String fileName)
  2. getFileFromChooserForPNG()
  3. getFileFromChooserSave()
  4. getFileName(Component parent)
  5. getFileOrDir(String startName, boolean fileSelect)
  6. getFilePath(Component parent, JFileChooser fileChooser, String title, FileFilter filter)
  7. getFiles(String title, String initialRoot, String initialFile)
  8. getFilesToOpen(File startDirectory, Component parent, String... filters)
  9. getFileToSave(String description, String extension, Component component)