Java获取所选文件夹路径

时间:2017-09-11 16:28:31

标签: java swing

在应用程序中我要求用户选择文件夹但是使用下面的代码我无法将此输入用作变量路径

public class csvtoxls {

    public static void main() throws IOException {

        JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
        jfc.setDialogTitle("Wybierz folder do konwersji: ");
        jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        jfc.setAcceptAllFileFilterUsed(false);
        int returnValue = jfc.showSaveDialog(null);
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            if (jfc.getSelectedFile().isDirectory()) {
                System.out.println("You selected the directory: " + jfc.getSelectedFile());

所以为了达到这个目的,我使用了函数:

public class getpath {

      public static String pickPath(JFileChooser fileChooser)
      {
        String path = null;

        /* create a JFrame to be the parent of the file 
         * chooser open dialog if you don't do this then 
         * you may not see the dialog.
         */
        JFrame frame = new JFrame();
        frame.setAlwaysOnTop(true);

        // get the return value from choosing a file
        int returnVal = fileChooser.showOpenDialog(frame);

        // if the return value says the user picked a file 
        if (returnVal == JFileChooser.APPROVE_OPTION)
          path = fileChooser.getSelectedFile().getPath();
        return path;

      }
}

变量:

Path workDir = Paths.get(getpath.pickPath(jfc));

这个解决方案的问题是用户必须选择两次文件夹,这很容易导致错误。有没有办法让这条路更容易?

0 个答案:

没有答案