Opening Finder / Explorer using Java Swing

I am creating an application in which it would be very easy for a user to click a link in an application that will open a specific folder in Finder (on Mac) / Windows Explorer. This can happen when an event is clicked on a link or button.

Is there a way to open these own OS (for a specific folder) through Swing?

+4
source share
2 answers

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

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

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

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

 open /users/ 

you can find out how to determine which OS you are on, and therefore which code to run, here . For example, it will look if you are in windows:

 public static boolean isWindows() { String os = System.getProperty("os.name").toLowerCase(); // windows return (os.indexOf("win") >= 0); } 
+9
source

Short answer:

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

Long answer: Although reading which OS it is, and then launching a specific operating system, will work, this is largely due to hard coding of what needs to be done.

Let Java handle how each OS should open directories. There should not be our headache. <3 abstractions.

Reading the #open (File) document shows that it will open a link to all operating systems that support this operation. If the current platform does not support opening folders or files (say, a headless environment, of course, my guess as to why it does not open is a hypothesis), it will throw an UnsupportedOperationException . If the user does not have read access to the folder (Windows Vista / 7/8, Unix-based machines), you will receive a SecurityException . Therefore, if you ask me, it is pretty well crafted.

Update: Added an if check before retrieving the Desktop object so that your code is saved from the disgusting HeadlessException and UnsupportedOperationException , as specified in the #getDesktop () Java Documentation .

+22
source

Source: https://habr.com/ru/post/1433230/


All Articles