Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a File in default File explorer and highlight it using JavaFX or plain Java

I wish to do what the title says.


Part Solution:

For example in Windows you can use the code below to open a file in the default explorer and highlight it.

(although it needs modification for files containing spaces):

/**
 * Opens the file with the System default file explorer.
 *
 * @param path the path
 */
public static void openFileLocation(String path) {
    if (InfoTool.osName.toLowerCase().contains("win")) {
        try {
            Runtime.getRuntime().exec("explorer.exe /select," + path);
        } catch (IOException ex) {
            Main.logger.log(Level.WARNING, ex.getMessage(), ex);
        }
    }
}

Useful Links:

Links which are similar but no way dublicates or not answered:

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

Open a folder in explorer using Java

How can I open the default system browser from a java fx application?


More explanation:

  • Is there a way to do it using JavaFX ?

      If not at least i need a link or some way to make the app system  
       independence.I mean i don't know the default explorer for every OS     
       that the application is going to work , i need a link or help doing that.
    
  • Do i need to write a ton of code to do this?

  • Is out there any library for doing that?

  • Do Java9 support that?


Finally:

It is very strange that for so common things i can't find answers and libraries .


Example of highlighted or selected in Windows 10:

enter image description here

like image 847
GOXR3PLUS Avatar asked Dec 04 '16 21:12

GOXR3PLUS


People also ask

How to open a file explorer in Java?

Opening file explorer with java in any platform – Windows, Linux and Mac. The easiest way to do this is by using Java Desktop. The class provides an open() function Desktop#open(File) to open explorer when the given file is a directory. From Java 9 onwards, Desktop is available on the java.

How do I open file explorer in R?

Another method we know for opening File Explorer or File Explorer is to use the good old Run window. Launch Run (a quick way to do that is to press the Win + R keys) and enter the word explorer in it. Then click or tap on OK, or press Enter on your keyboard.


1 Answers

Windows

Runtime.getRuntime().exec("explorer /select, <file path>")

Linux

Runtime.getRuntime().exec("xdg-open <file path>");

MacOS

Runtime.getRuntime().exec("open -R <file path>");
like image 118
远星河 Avatar answered Nov 03 '22 01:11

远星河