首页 > 解决方案 > Java Desktop.open() 永远不会完成

问题描述

这是一个永远不会完成的代码示例。我所做的就是用 Desktop.open(file) 打开一个文件。关闭打开的文件(例如弹出的文本编辑器或 excel 文件)后程序关闭。

public static void main(String[] args) {
    File file = new File("TextFile1.log");
    if (file.exists()) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                Desktop desktop = Desktop.getDesktop();
                System.out.println("opening using desktop protocol " + desktop.toString());
                try {
//                  Runtime.getRuntime().exec("gedit "+file);//this line of code works fine, but it is linux related
                    desktop.browse(file.toURI());//
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                System.out.println("File opened " + file.getName());
            }
        };
        thread.start();
    } else {
        System.out.println("File does not exists!");
    }
    try {
        Thread.sleep(1000L);//just so we do not exit before file is actually opened
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("End of program.");
    System.exit(0);
}

我得到的输出:

opening using desktop protocol java.awt.Desktop@7a8afb69
File opened TextFile1.log
End of program.

一段时间后,我决定关闭打开的文件,并且在输出中也得到以下行:

Process finished with exit code 0

如何在不阻止退出的情况下打开文件并且支持跨平台?

我在 Windows 上也注意到了这一点。全部在 Java 8 上。

标签: java

解决方案


推荐阅读