java:点击按钮打开文件夹

C g*_*ics 6 java windows api directory

在java中,我们如何在点击按钮时为用户打开一个单独的文件夹(例如c :),例如像我们下载文件时"在磁盘上找到此文件"或"打开包含文件夹"的方式,我们想要知道它被保存的地方.目标是节省用户打开浏览器的时间并在磁盘上找到该文件.谢谢(下面的图片是firefox所做的一个例子) 在此输入图像描述

我得到了答案:这是在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) {
        }
Run Code Online (Sandbox Code Playgroud)

感谢@AlexS

Ale*_*exS 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

但我不知道支持哪些平台.