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

8

53

I am now using java Desktop API to manipulate file explorer. I know how to open the file explorer but I don't know how to open it and highlight the specified file.

As we using the Chrome, after downloading files, we can choose "show in folder" to open the file explorer and highlight the downloaded file.

How to use java Desktop API to do so? Or is there any other API in java can realize this action?

Undershoot answered 9/9, 2011 at 6:36 Comment(1)
I read every answers and comments of my question, but there are no satisfied answers. I vote some answers which close to my aim, though those are not the complete solutions. So I didn't accept any answers to prevent others misunderstood. Hope someone someday can give me a complete solution of those questions, and of course, I will accept. At last, I invite to you to join my discussions. Maybe you are the one who can solve my questions. Thanks for your comment.Undershoot
C
57

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

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

Curtate answered 8/9, 2014 at 14:22 Comment(5)
Hi @Stone, your code really works. But the quot should be modified. Runtime.getRuntime().exec("explorer.exe /select, path")Undershoot
@CharlesWu You are actually both correct. @Curtate refers to the variable path which contains the entire path, while yours is simply the String "path" (which is invalid in every(?) system, but it compiles).Dorty
@Curtate i need to highlight multiple file.. then how can i do? you have any idea?Coroneted
@AkashChavda no for now i don't have any idea how to achieve this.Curtate
Runtime.exec() is deprecated since Java 18 (bugs.openjdk.org/browse/JDK-8276412), check out my answer for a ProcessBuilder solutionGeryon
P
43

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 and http://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.

Parabolize answered 27/12, 2012 at 4:38 Comment(7)
When I asked the question, I use the jdk 6. With the time going by, the new version of java is powerful for developers. Any way, thanks for answer my question.Undershoot
Your welcome. @krok has a good answer, but I thought I would add my 2 cents in the spirit of platform independence.Parabolize
This is not supported on Windows 10 or Linux (at least CentOS 7 + Gnome).Liquefy
Doesn't work with Debian Linux either. What does it work on? Anyway, here's a ticket that describes this: bugs.openjdk.java.net/browse/JDK-8233994Tolmann
Desktop.getDesktop.open(file) works for me in Windows 10 using Java 8.Bedfast
Note that this does not work with a console application, mine is a spring webapp, a java.awt.HeadlessException will throw.Gunning
@Gunning correct, in a "headless" environment this will not work. You can check if the execution environment is headless by calling '''GraphicsEnvironment.getLocalGraphicsEnvironment().isHeadless()'''. If you are using X11 forwarding then it's possible that this may return false and it will actually work from a console app.Parabolize
V
28

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();
Vinic answered 10/9, 2011 at 4:12 Comment(3)
this open my home folder when the path have a whitespace :(Windgall
@Windgall you will have to escape spaces in your command line optionsVinic
As @Geryon mentions below, you need to put "/select," and "C:\\directory\\selectedFile" as separate Strings (that's the only way it worked for me anyway!)Bedfast
C
3

We can open a specific path from command line with :

start C:/ProgramData

There are two ways in java you can use to open windows explorer with specific path:

  1. Use Process class(as already answered) but with start command

    try {
        Process builder = Runtime.getRuntime().exec("cmd /c start C:/ProgramData");
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  2. Use Desktop class

    try {
        Desktop.getDesktop().open(new File("C:/ProgramData"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    
Catarinacatarrh answered 12/9, 2016 at 7:19 Comment(1)
I liked this solution because I use Directory Opus instead of explorer and with start command you can get your default file manager and not explorer!!!Lagasse
M
2

Always use the "\" instead of "/", otherwise only the Explorer will open, fore more read this - Command-line switches that you can use to open the GUI Windows Explorer (Explorer.exe)

Using Windows CLI :

C:\Users\Md Arif Mustafa>explorer.exe /select, "C:\Users\Md Arif Mustafa\Music\Aafreen-Himesh.mp3"

Same in Java source code : Here variable filePaths is an ArrayList<String> and contains a folder all files path.

try {
    Process proc = Runtime.getRuntime().exec("explorer.exe /select, " + filePaths.get(i).replaceAll("/", "\\\\"));
    proc.waitFor();
} catch (IOException | InterruptedException ex ) {
    ex.printStackTrace();
}

It worked for me and hope it helps you!

Multitude answered 9/11, 2017 at 9:58 Comment(0)
D
1

This works even if file/folder name has multiple spaces between words.

    //In this example there are 3 spaces between "GAME" and "OF" and 2 spaces between "OF" and "Thrones"
    String onlyPath = "D:\\GAME   OF  Thrones";
    String selectPath = "/select," + onlyPath;        

    //START: Strip one SPACE among consecutive spaces
    LinkedList<String> list = new LinkedList<>();
    StringBuilder sb = new StringBuilder();
    boolean flag = true;

    for (int i = 0; i < selectPath.length(); i++) {
        if (i == 0) {
            sb.append(selectPath.charAt(i));
            continue;
        }

        if (selectPath.charAt(i) == ' ' && flag) {
            list.add(sb.toString());
            sb.setLength(0);
            flag = false;
            continue;
        }

        if (!flag && selectPath.charAt(i) != ' ') {
            flag = true;
        }

        sb.append(selectPath.charAt(i));
    }

    list.add(sb.toString());

    list.addFirst("explorer.exe");
    //END: Strip one SPACE among consecutive spaces

    //Output List
    for (String s : list) {
        System.out.println("string:"+s);
    }
    /*output of above loop

    string:explorer.exe
    string:/select,D:\GAME
    string:  OF
    string: Thrones

    */

    //Open in Explorer and Highlight
    Process p = new ProcessBuilder(list).start();
Danella answered 24/4, 2016 at 4:54 Comment(0)
S
1

Here is shorter version of above.

    String onlyPath = "D:\\GAME   OF  Thrones";
    String completeCmd = "explorer.exe /select," + onlyPath;
    new ProcessBuilder(("explorer.exe " + completeCmd).split(" ")).start();
Serif answered 4/5, 2017 at 11:49 Comment(0)
G
1

The correct ProcessBuilder code is actually the following:

public static void selectFileInFileExplorer(final Path filePath) throws IOException {
    final String windowsDirectory = System.getenv("WINDIR");
    final String explorerFilePath = windowsDirectory + "\\explorer.exe";
    final ProcessBuilder builder = new ProcessBuilder(explorerFilePath, "/select,", filePath.toString());
    builder.start();
}

Note that you need to start a new command after /select,, otherwise it will open the Documents folder.

Geryon answered 23/4, 2023 at 15:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.