desktop.open in Java opens .bat file instead of a folder

Viewed 53
File file = new File ("D:\\Folder\\Folder2\\");
Desktop desktop = Desktop.getDesktop();
try {
    desktop.open(file);
} catch (IOException e) {
    e.printStackTrace();
}

The following code supposed to open Folder2, but instead it opens D:\Folder\Folder2.bat file. How to fix that?

2 Answers

Opening folder through Deskopt.open() would be delegated to Desktop.browseFileDirectory() (JDK 8/9)

But, as seen in JDK-8233994, that is not supported/implemented for Windows.

So the alternative with explorer.exe is indeed the recommended way:

Process p = new ProcessBuilder("explorer.exe", "/select,D:\\Folder\\Folder2").start();

The Desktop API describes the method open() clearly:

Launches the associated application to open the file. If the specified file is a directory, the file manager of the current platform is launched to open it.

Or see the reply of @vonC

Related