使用JavaFX或纯Java,在默认文件浏览器中打开文件并将其突出显示。

6

我希望能够根据标题所说的做到。


部分解决方案:

例如在Windows中,您可以使用以下代码打开默认资源管理器并突出显示文件。

(尽管它需要修改来处理包含空格的文件):

/**
 * 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);
        }
    }
}

有用的链接:

这些链接类似,但是并不重复或没有回答:

如何使用Java代码打开Windows文件资源管理器并突出显示指定的文件?

使用Java打开资源管理器中的文件夹

如何从Java FX应用程序中打开默认系统浏览器?


更多解释:

  • 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?


最后:

很奇怪的是,对于如此普遍的事情,我找不到答案和库。


在Windows 10中选择或突出显示的示例:

enter image description here


1
“在Windows 10中突出显示或选择的示例:” - 是的,Java无法访问在Windows环境中运行的应用程序的单独API。我相信你需要一种更低级别的语言来实现这个功能。 - camickr
我个人认为你对JavaFX有所困惑。它仅用于处理图形用户界面的创建。您需要使用其他库来添加功能。JavaFX不是实用API。JavaFX旨在取代Swing成为Java SE标准GUI库。 - SedJ601
1
作为JavaFX不断发展,我认为它可能会通过JNI调用本地系统来呈现这样的功能或库。如果能提供这样的功能,那么实际上将是令人惊叹的。任何解决方案,包括第三方库,都将被高度接受。你可以看到Swing有Desktop API。 - GOXR3PLUS
1
真的很遗憾这个问题没有得到解答。我有完全相同的需求。 - ice1000
1
签名。不同的机器有不同的文件浏览器,我不知道如何适应更多的操作系统。 - ice1000
显示剩余8条评论
4个回答

4
自Java 9起,使用新方法browseFileDirectory即可实现,因此您的方法应该如下所示:
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));
}

欲了解更多信息,请参考javadoc: https://docs.oracle.com/javase/10/docs/api/java/awt/Desktop.html#browseFileDirectory(java.io.File)


太棒了,只有一个问题,它也会在资源管理器中选择文件吗? - GOXR3PLUS
1
Oracle文档说可以。我在Windows7上测试过,可以运行。但是在我的Manjaro Linux i3社区版中,由于平台不支持该操作,会抛出异常,但我认为在KDE或Gnome上应该可以正常工作。 - bichoFlyer
完美的,我会进行测试 :) - GOXR3PLUS
3
在Windows 10上进行测试时出现了以下错误:java.lang.UnsupportedOperationException: The BROWSE_FILE_DIR action is not supported on the current platform!,我感到很惊讶。这里使用的是Java 9.0.4版本。 - GOXR3PLUS
2
请参见JDK-8233994。Windows 10故意不受支持。不知道为什么。也许只是被遗忘了。 - Hendrik

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>");

请注意,explorer "/select,<文件路径>"对于包含逗号字符的文件路径无效。 - rednoah

1
以下是部分答案,展示如何打开您所需的系统文件夹,但不展示如何突出显示特定文件,因为我认为在系统文件夹中突出显示文件可能是系统操作功能,无法通过Java访问。
这是用Javafx编写的代码。
在您的Main类中,创建一个Hostservices变量。请注意,“yourFileLocation”是文件夹到文件的地址,SettsBtn是某个存在的按钮,用户单击该按钮以执行代码。
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());
        });
    }
}

请注意,您可以通过将文件位置和文件名及其扩展名组成的字符串直接打开文件,例如:
Path partPath = Paths.get("yourFileLocation"+"\\"+"yourFileName.ext");

在Chrome中显示:D - Alex

1
截至Java 17,Windows 10或更高版本仍未支持Desktop :: browseFileDirectory方法。历史原因是,当Apple自己还在为Mac OS X维护JDK时,Apple最初实现了这些本机桌面集成功能的com.apple.eawt包。所有这些都在Java 9中作为JEP 272:特定于平台的桌面功能移植到java.awt.Desktop中,因此我想这些功能到今天为止仍然只针对Mac OS X实现。幸运的是,Windows 10确实有一个SHOpenFolderAndSelectItems函数,我们可以通过JNA调用它,如下所示:
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());
        }
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接