java: Open folder on button click

泄露秘密 提交于 2019-12-22 05:46:22

问题


In java, how can we open a separate folder (e.g. c:) for user on click of a button, e.g like the way " locate this file on disk" or "open containing folder" does when we download a file and we want to know where it was saved. The goal is to save user's time to open a browser and locate the file on disk. Thanks ( image below is an example from what firefox does)

I got the answer: Here is what worked for me in 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) {
        }

Thanks to @AlexS


回答1:


I assume you have a file. With java.awt.Desktop you can use something like this:

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);
    }
}

Be awrae that if you call this with a File that is no directory at least Windows will try to open the file with the default program for the filetype.

But I don't know on which platforms this is supported.



来源:https://stackoverflow.com/questions/9134096/java-open-folder-on-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!