Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: Open folder on button click

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) enter image description here

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

like image 552
C graphics Avatar asked Feb 03 '12 19:02

C graphics


1 Answers

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.

like image 128
AlexS Avatar answered Oct 21 '22 19:10

AlexS