Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening Finder/Explorer using Java Swing

I am creating an application in which it would be very easy for a user to actually be able to click on a link in the application, which opens up a specific folder in Finder (in Mac)/ Windows Explorer. This can happen on click event of a link or a button.

Is there a way I can open these native OS applications (for a specific folder) via Swing?

like image 483
Rohan Avatar asked Sep 09 '12 14:09

Rohan


2 Answers

Short Answer:

if (Desktop.isDesktopSupported()) {
    Desktop.getDesktop().open(new File("C:\\"));
}

Long Answer: Though reading what OS it is and then running an OS specific command would work, it entails, to an extent, hard coding of what needs to be done.

Let Java handle how each OS should open directories. Shouldn't be our headache to take. <3 abstraction.

Reading the #open(File) method documentation reveals that it will open the link on all OS' which support the operation. If the current platform doesn't support opening of folders or files (say a headless environment? of course, my guess as to why it won't open is conjecture), it will throw an UnsupportedOperationException. If the user doesn't have access to read the folder (Windows Vista/7/8, Unix based machines), you will get a SecurityException. So if you ask me, it's rather well handled.

Updated: added an if check before getting the Desktop object so that your code is saved from nasty HeadlessException and UnsupportedOperationException exceptions as mentioned in the #getDesktop() Java Documentation.

like image 96
javatarz Avatar answered Oct 17 '22 08:10

javatarz


Use Runtime.getRuntime().exec("command here"); to execute a command in the system on which java is running.

For explorer.exe, you can simply pass the absolute path of the folder as an argument, e.g.

Explorer.exe "C:\Program Files\Adobe"

In Mac OS X, you can use the open command:

open /users/

you can find out how to detect which OS You're on, and hence which code to run, here. For example, this will chek if you are on windows:

public static boolean isWindows() {

    String os = System.getProperty("os.name").toLowerCase();
    // windows
    return (os.indexOf("win") >= 0);

}
like image 28
Jakob Weisblat Avatar answered Oct 17 '22 07:10

Jakob Weisblat