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?

Answers


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

}

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.


Need Your Help

Parse XML to get node value

xml vb.net xml-parsing

I want to parse XML string like this one:

Pass parameters by adress to Macros in Assembly 8086 MASM

assembly macros parameters 8086

I have a macro to read user input using Interrupt Int 21,A.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.