How to use java code to open Windows file explorer and highlight the specified file? How to use java code to open Windows file explorer and highlight the specified file? windows windows

How to use java code to open Windows file explorer and highlight the specified file?


Use: Runtime.getRuntime().exec("explorer.exe /select," + path);

This also works if there is a space in the PATH.


EDIT:

As of java 9 there is now a method in the Desktop API to select the file

desktop.browseFileDirectory(<file>)

EDIT:

You cannot highlight a specific file with the java Desktop API.

ANSWER TO ORIGINAL QUESTION:

The Desktop API will allow you to do this by using this snippet,

File file = new File ("c:\<directory>");Desktop desktop = Desktop.getDesktop();desktop.open(file);

The documentation for the code used above is at these links, http://docs.oracle.com/javase/10/docs/api/java/awt/Desktop.html andhttp://docs.oracle.com/javase/10/docs/api/java/io/File.html

On a Windows computer this will open the default file explorer and on other systems it will open their default explorers respectively.

Alternatively you could use the new java Path API to build the required path and then invoke the method that returns the corresponding File object.

For brevity I excluded the checking code to make sure the Desktop and File objects exist.


The Desktop API does not support this. You are going to have to use ProcessBuilder (or alternatively Runtime.exec()) to execute explorer.exe explicitly with the options you want. This will only work on windows though, if you want to run this on another OS you will have to use the Desktop API anyway.

Process p = new ProcessBuilder("explorer.exe", "/select,C:\\directory\\selectedFile").start();