【问题标题】:jfilechooser - set directory to a path in a filejfilechooser - 将目录设置为文件中的路径
【发布时间】:2011-04-19 19:19:35
【问题描述】:

我正在尝试通过类似这样的方式(使用 commons-io)在 JFilechooser 中设置目录路径:

String fileContents = IOUtils.toString(new FileInputStream("path.txt"));
File theDirectory = new File(fileContents);

filechooser = new JFileChooser();
fileChooser.setCurrentDirectory(theDirectory);
filechooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

我使用getCanonicalPath()获取路径并写入文件path.txt

path = file.getCanonicalPath();

我不打算把我所有的代码都放在这里,但我确信程序会在 path.txt 中写入和读取路径。 我没有收到任何错误,但每次我运行程序时,它总是在我的文档文件夹中打开 JFilechooser。我做错了什么?

【问题讨论】:

  • 您是否尝试打印出theDirectory 以及它是否存在? System.out.println( theDirectory.getCanonicalPath() + " exists: " + theDirectory.exists() ); 如果文件不再存在,则文件选择器将默认为 My Documents 文件夹。

标签: java swing jfilechooser


【解决方案1】:

在你的主类中声明

public static String dirpath=".";

private void btnBrowseActionPerformed(java.awt.event.ActionEvent evt) {    
 JFileChooser jfc = new JFileChooser(dirpath);
 dirpath =jfc.getSelectedFile().getAbsolutePath().toString();
}

【讨论】:

    【解决方案2】:

    尝试在构造函数中直接传递当前目录:

    filechooser = new JFileChooser(theDirectory);
    

    【讨论】:

      【解决方案3】:

      如果您咨询API,使用默认构造函数(即new JFileChooser()):

      构造一个指向的 JFileChooser 用户的默认目录。这个 默认取决于操作 系统。它通常是“我的 Windows 上的 Documents”文件夹,以及 Unix 上用户的主目录。

      似乎可以解释总是打开我的文档,但这不是你的问题。其实你的问题在于设置当前目录(即setCurrentDirectory(theDirectory)):

      设置当前目录。传入 null 设置文件选择器指向 用户的默认目录。这个 默认取决于操作 系统。它通常是“我的 Windows 上的 Documents”文件夹,以及 Unix 上用户的主目录。 如果 作为 currentDirectory 传入的文件是 不是目录,它的父级 文件将用作 当前目录。如果父母不在 可遍历的,然后它将向上走 直到找到一个父树 可遍历目录,或点击 文件系统的根目录。

      话虽如此,我会注意 突出显示的文本,因为您似乎将 file 设置为当前目录,而不是 目录

      【讨论】:

      • 我没有将文件设置为当前目录。我正在尝试使用最后选择的目录设置当前目录 File file = fileChooser.getSelectedFile();即使我关闭程序并再次运行它,我也要始终打开文件选择器并选择最后一个目录
      • @fermk090:那么你将不得不持久化last directory selected,当你再次运行程序时,加载持久化的目录。
      • 我认为这就是他正在做的事情。他将位置保存到“path.txt”并恢复它。
      【解决方案4】:

      选择您打开的最后一个目录:

      chooser.setCurrentDirectory(lastDirectory);
      
      int r = chooser.showOpenDialog(new JPanel());
      
      if (r == JFileChooser.APPROVE_OPTION) {
         fileName = chooser.getSelectedFile().getPath();
         lastDirectory = chooser.getSelectedFile();
      }
      

      【讨论】:

        【解决方案5】:

        JFileChooser 选择器 = new JFileChooser("F:");

        【讨论】:

          【解决方案6】:

          如果要更改目录,请使用 System.getProperty 方法

          String s=System.getProperty("user.dir");  // changes directory from documents to the user current Directory;
          

          JFileChooser jfc=new JFileChooser(s);

          【讨论】:

            猜你喜欢
            • 2019-12-21
            • 1970-01-01
            • 2021-10-07
            • 2015-12-26
            • 2016-02-02
            • 1970-01-01
            • 2019-11-08
            • 2020-04-14
            相关资源
            最近更新 更多