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?
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With