在ubuntu(linux)上从java打开一个带有Desktop.open()的路径

mic*_*mit 7 java ubuntu desktop path

从我用java编写的应用程序我想打开一个文件夹,使用操作系统文件资源管理器.

我使用Desktop.open(新文件(路径))

这在windows上工作正常,但在ubuntu 11.10(linux)上它不起作用.使用Desktop.open打开文件确实可以在ubuntu和windows上运行.

使用介于两者之间的步骤:文件fPath = new File(fPath)并使用fPath.exists()和fPath.isDirectory()测试它们都给出了true.

使用Desktop.open(新文件(路径))给我这个例外:

java.io.IOException: Failed to show URI:file:/and/here/the/path/I/use/
at sun.awt.X11.XDesktopPeer.launch(Unknown Source)
at sun.awt.X11.XDesktopPeer.open(Unknown Source)
at java.awt.Desktop.open(Unknown Source)
Run Code Online (Sandbox Code Playgroud)

我还没能在苹果电脑上测试这个,但我希望Desktop.open(新文件(路径))是系统独立的......

顺便说一句,完整的代码:

    Desktop desktop = null;
    // Before more Desktop API is used, first check
    // whether the API is supported by this particular
    // virtual machine (VM) on this particular host.
    if (!Desktop.isDesktopSupported()) {
        // show Error
        return;
    }
    desktop = Desktop.getDesktop();
    String path = "here the path ";
    // by the way: I use System.getProperty("file.separator") as file seperator
    try {
        File fPath=new File(path);
        if(!fPath.exists()){
            // show Error
            return;

        }
        if(!fPath.isDirectory()){
            // show Error
            return;

        }
        desktop.open(new File(path));
    } catch (IOException e) {
        log.severe(e.getMessage());
        e.printStackTrace();
        // show Error
        return;
    }
Run Code Online (Sandbox Code Playgroud)

一些额外的信息:操作系统:Linux(3.0.0-16-通用 - amd64)

Java:1.6.0_30-b12

Java home:/opt/java/64/jre1.6.0_30

小智 5

我有同样的问题。但就我而言,它是 Ubuntu 18.04 和 java 1.8.0_161-b12 在 Windows 10 中,一切正常。但是在 Ubuntu 上

Desktop.getDesktop().open(new file) 
Run Code Online (Sandbox Code Playgroud)

程序停止响应。我决定将调用包装在执行程序中:

private ExecutorService executorService; 
   BasicThreadFactory factory = new BasicThreadFactory.Builder()
            .namingPattern("YourPatternIndeficator")
            .build();
    executorService = Executors.newSingleThreadExecutor(factory);
if (Desktop.isDesktopSupported()) {
        File myFile = new File(path);
        executorService.execute(() -> {
            try {
                Desktop.getDesktop().open(myFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

    }
Run Code Online (Sandbox Code Playgroud)


f4l*_*lco 0

我无法确认该错误。我获取了你的代码并围绕它构建了一个主要方法,一切都按预期工作。我不完全知道默认应用程序的设置位置(在我的例子中,打开的是 PCMan,而不是通常的 Nautilus,但它最终应该实现其目的)。

\n

在 java.awt.Desktop.open 上,\xe2\x80\x99t 不能处理 PDF 文件吗?我发现了一个指向Suns (Oracles) bug tracker 中的问题的链接,指出使用 AWT 打开文件的方法即使在 Windows 上也不可靠。也许您应该考虑打开此类应用程序的其他方法。此外,几乎可以肯定的是,AWT 很快就会被弃用。

\n

如果您在应用程序中使用 SWT,则可以使用org.eclipse.swt.program.Program.

\n