如何使用 Java 从 windows 文件资源管理器 return 文件路径

How to return the file path from the windows file explorer using Java

在我的项目中,我想用 java 打开 windows 文件资源管理器,您可以在其中 select 一个文件或文件夹,然后单击“确定”按钮。现在我想在我的 Javacode 中包含 selected 文件的路径。

基本上就像点击“OPEN”按钮选择要在编辑器中打开的文件后,每个标准文本编辑器中弹出的 window。

我知道如何使用 Runtime.getRuntime().exec("explorer.exe") 打开 windows 文件资源管理器,但我无法找到 return 文件路径的方法。

这就是我如何使用 JFileChooser 来解决您的问题:

String filePath;    // File path plus name and file extension
String directory;        // File directory
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        directory = fc.getSelectedFile().getName();
    } else {
        directory = "Error in selection";
    }
filePath = directory + "\" + folderName;

最好的选择是在javax.swing.JFileChooser中使用JFileChooserclass。它是一个 Java swing 对象,因此它不会调用本机 OS 的文件浏览器,但它在选择 file/saving 到某个位置方面做得很好。看看这个 link 的基本实现。

我在我的代码中使用了 link 中的这个方法:

public static Path getInputPath(String s) {
        
         /*Send a path (a String path) to open in a specific directory
         or if null default directory */
         JFileChooser jd = s == null ? new JFileChooser() : new JFileChooser(s);

         jd.setDialogTitle("Choose input file");
         int returnVal= jd.showOpenDialog(null);

         /* If user didn't select a file and click ok, return null Path object*/
         if (returnVal != JFileChooser.APPROVE_OPTION) return null;
         return jd.getSelectedFile().toPath();
    
    }

请注意,此方法 returns 是 Path 对象,而不是 String 路径。这可以根据需要更改。