6

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

Nimantha
  • 6,405
  • 6
  • 28
  • 69
GOXR3PLUS
  • 6,877
  • 9
  • 44
  • 93
  • I am ready to give bounty for the brave who will find the answer ;) – GOXR3PLUS Dec 04 '16 at 21:44
  • `I mean i don't know the default explorer for every OS that the application is going to work ` - That is what the `Desktop` API is for. You already linked to and answer with that solution. So what is wrong with that class? – camickr Dec 04 '16 at 21:44
  • @camickr Hello camickr . First it is using `Swing Library` , Second it just opens the file in the default explorer and no way i can highlight it . It only answers partially the question and is using different Framework which is causing problems and it is soon to be obsolete. – GOXR3PLUS Dec 04 '16 at 21:45
  • What is the difference between plain Java and Swing? The Swig API is part of the base JDK. What do you mean highlight? – camickr Dec 04 '16 at 21:46
  • 1
    `Example of highlighted or selected in Windows 10:` - yes well Java doesn't have access to the individual API of a application that runs in a Windows environment. I'm sure for this you need a lower level language. – camickr Dec 04 '16 at 21:51
  • @camickr I added an image . Yes it is part of the JDK(althought it is very awesome it will soon not be , maybe it is 5 years or sooner) . It doesn't fit well along with `JavaFX` . I need something which will stay . – GOXR3PLUS Dec 04 '16 at 21:51
  • The first linked answer you posted has two options of achieving what you are looking for. Beyond that, you can create a javafx window which list all the files of a folder and highlights the appropriate file. This second approach will require a lot of coding. – SedJ601 Dec 05 '16 at 03:39
  • I personally think that you are confused about JavaFx. It only handles GUI creation. You have to use other libraries to add functionality. JavaFx is not a utility API. JavaFX was intended to replace Swing as the standard GUI library for Java SE – SedJ601 Dec 05 '16 at 03:43
  • @Sedrick Jefferson The first link has the answer only for `Windows` and it actually not working well in some cases . A more complete approach with links for other operating system will be excellent . – GOXR3PLUS Dec 05 '16 at 04:01
  • 1
    @Sedrick Jefferson As JavaFX continues to envolve i think it may present a functionality or library like this , by calling the native System through JNI. Actually it will be amazing if such a feature is presented . Any solution including third party libraries is highly accepted . You can see that Swing has Desktop API. – GOXR3PLUS Dec 05 '16 at 04:03
  • 1
    It's really a pity that this isn't answered. I have exactly the same need. – ice1000 Apr 16 '18 at 09:01
  • @ice1000 For windows you can use the code added on question, for Linux and Mac, well '' wait till i find the answer son :) '' – GOXR3PLUS Apr 16 '18 at 14:39
  • 1
    Sign. Difference machine has difference file explorer, and I have no idea how to adapt more OSs. – ice1000 Apr 17 '18 at 00:57

4 Answers4

4

Windows

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

Linux

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

MacOS

Runtime.getRuntime().exec("open -R <file path>");
Dr-Bracket
  • 4,299
  • 3
  • 20
  • 28
远星河
  • 79
  • 1
  • Note that `explorer "/select,"` doesn't work for file paths that happen to contain a `,` character. – rednoah Jul 23 '22 at 19:46
3

Since Java 9 it's possible with the new method browseFileDirectory, so your method would state:

import java.awt.Desktop;
import java.io.File;
...

/**
 * Opens the file with the System default file explorer.
 *
 * @param path the path
 */
public static void openFileLocation(String path) {
    Desktop.getDesktop().browseFileDirectory(new File(path));
}

For more information, refer to the javadoc: https://docs.oracle.com/javase/10/docs/api/java/awt/Desktop.html#browseFileDirectory(java.io.File)

Nimantha
  • 6,405
  • 6
  • 28
  • 69
bichoFlyer
  • 178
  • 9
  • That's awesome, just one question, it also selects the file in the explorer? – GOXR3PLUS Jun 25 '18 at 15:39
  • 1
    The oracle documentation says yes. I've tested on windows7 and works. In my manjaro linux i3 community edition throws an exception since the platform doesn't support the operation, but I think that on KDE or Gnome should work fine. – bichoFlyer Jun 25 '18 at 18:27
  • Perfect i will do tests :) – GOXR3PLUS Jun 25 '18 at 18:35
  • 3
    Just tested on Windows 10 .... `java.lang.UnsupportedOperationException: The BROWSE_FILE_DIR action is not supported on the current platform!` i am like whatttttt ...using Java 9.0.4 – GOXR3PLUS Jun 29 '18 at 04:47
  • 2
    See [JDK-8233994](https://bugs.openjdk.java.net/browse/JDK-8233994). Windows 10 is intentional not supported. No idea why. Perhaps it was simply forgotten. – Hendrik Nov 14 '19 at 06:56
1

The following is a partial answer showing you how to open the system folder you desire, but not how to highlight a specific file since I do not believe it is possible to highlight a file in a system folder, because that is probably a system OS function that cannot be accessed by Java.

This is written in Javafx code

In your Main class make a variable for Hostservices. Note that "yourFileLocation" is the address of the folder to the file, and SettsBtn is a button that exists somewhere which the user clicks to execute the code:

public class Main extends Application{

    static HostServices Host; //<-- sort of a global variable

    //some code here to make your GUI

    public Main() {
        //more code here to initialize things
    }

    public void start(Stage primaryStage) throws Exception {
        //some code here to set the stage

        //This code here opens the file explorer
        SettsBtn.setOnMouseClicked(e-> {
            Path partPath = Paths.get("yourFileLocation");
            Host = getHostServices();
            Host.showDocument(partPath.toUri().toString());
        });
    }
}

Note that you could directly open the file by making a string to the file location and the file name with its extension, such as:

Path partPath = Paths.get("yourFileLocation"+"\\"+"yourFileName.ext");
Miss Chanandler Bong
  • 4,081
  • 10
  • 26
  • 36
alexcode
  • 19
  • 1
1

As of Java 17 the Desktop::browseFileDirectory method is still not supported on Windows 10 or later.

The historic reason is that Apple originally implemented these native Desktop integration features for Mac OS X in the com.apple.eawt package back when Apple itself was still maintaining the JDK for Mac OS X. All of that was ported into java.awt.Desktop for Java 9 as per JEP 272: Platform-Specific Desktop Features and so I guess some of these features are still only implemented for Mac OS X to this day.

Fortunately, Windows 10 does have a SHOpenFolderAndSelectItems function that we can call via JNA like so:

public interface Shell32 extends com.sun.jna.platform.win32.Shell32 {
    Shell32 INSTANCE = Native.load("shell32", Shell32.class, W32APIOptions.DEFAULT_OPTIONS);

    HRESULT SHParseDisplayName(WString pszName, Pointer pbc, PointerByReference ppidl, WinDef.ULONG sfgaoIn, Pointer psfgaoOut);
    HRESULT SHOpenFolderAndSelectItems(Pointer pidlFolder, WinDef.UINT cidl, Pointer apidl, WinDef.DWORD dwFlags);
}
public class Shell32Util extends com.sun.jna.platform.win32.Shell32Util {

    public static Pointer SHParseDisplayName(File file) {
        try {
            PointerByReference ppidl = new PointerByReference();

            // canonicalize file path for Win32 API
            HRESULT hres = Shell32.INSTANCE.SHParseDisplayName(new WString(file.getCanonicalPath()), null, ppidl, new WinDef.ULONG(0), null);
            if (W32Errors.FAILED(hres)) {
                throw new Win32Exception(hres);
            }

            return ppidl.getValue();
        } catch (Exception e) {
            throw new InvalidPathException(file.getPath(), e.getMessage());
        }
    }

    public static void SHOpenFolderAndSelectItems(File file) {
        Pointer pidlFolder = SHParseDisplayName(file);

        try {
            HRESULT hres = Shell32.INSTANCE.SHOpenFolderAndSelectItems(pidlFolder, new WinDef.UINT(0), null, new WinDef.DWORD(0));
            if (W32Errors.FAILED(hres)) {
                throw new Win32Exception(hres);
            }
        } catch (Exception e) {
            throw new InvalidPathException(file.getPath(), e.getMessage());
        }
    }

}
rednoah
  • 1,053
  • 14
  • 41