java:点击按钮打开文件夹

时间:2012-02-03 19:08:08

标签: java windows api directory

在java中,我们如何通过点击按钮为用户打开单独的文件夹(例如c :),例如“在磁盘上找到此文件”或“打开包含文件夹”的方式当我们下载文件并且想要知道保存的位置时会这样做。目标是节省用户打开浏览器的时间并在磁盘上找到该文件。 谢谢(下面的图片是firefox所做的一个例子) enter image description here

我得到了答案: 以下是Windows 7中对我有用的内容:

        File foler = new File("C:\\"); // path to the directory to be opened
        Desktop desktop = null;
        if (Desktop.isDesktopSupported()) {
        desktop = Desktop.getDesktop();
        }

        try {
        desktop.open(foler);
        } catch (IOException e) {
        }

感谢@AlexS

1 个答案:

答案 0 :(得分:10)

我假设你有一个文件。使用java.awt.Desktop,您可以使用以下内容:

public static void openContaiingFolder(File file) {
    String absoluteFilePath = file.getAbsolutePath();
    File folder = new File(absoluteFilePath.substring(0, absoluteFilePath.lastIndexOf(File.separator)));
    openFolder(folder);
}

public static void openFolder(File folder) {
    if (Desktop.isDesktopSupported()) {
        Desktop.getDesktop().open(folder);
    }
}

请注意,如果您使用无目录的文件调用此文件,则至少Windows将尝试使用文件类型的默认程序打开该文件。

但我不知道支持哪种平台。