使用Java上的外部应用程序打开文件

问题描述:

如果您不知道文件与哪个应用程序相关联,那么如何从java应用程序打开文件。另外,因为我使用的是Java,所以我更喜欢独立于平台的解决方案。使用Java上的外部应用程序打开文件

使用JDK1.6,java.awt.Desktop类可能会有用。

public static void open(File document) throws IOException { 
    Desktop dt = Desktop.getDesktop(); 
    dt.open(document); 
} 
+0

这段代码是否也适用于linux? – 2017-07-23 14:58:42

+0

是的......但最好先调用`Desktop.isDesktopSupported()`或`Desktop.isSupported(action)`,参见Javadoc。 – RealHowTo 2017-07-27 19:55:52

你可以用Windows上的bat文件和Unix上的bat文件破解一些东西,但那不会很有趣。

我认为你最好的选择是JDesktop Integration Components (JDIC)。特别是,Desktop类具有您正在寻找的方法。

编辑:显然,我落后于时代,因为这已经集成到Java 1.6中。无论如何,如果你正在使用早期的Java,它可能仍然有用。

+0

提供的链接已损坏。你需要解决这两个问题。谢谢。 – 2008-12-24 04:39:49

File file 
Desktop.getDesktop().open(file); 

由于Java 1.6

此之前,你可以check this question

摘要

这将是这个样子:

Runtime.getRuntime().exec(getCommand(file)); 

public String getCommand(String file){ 
    // Depending on the platform could be 
    //String.format("gnome-open %s", fileName) 
    //String.format("open %s", fileName) 
    //String.format("cmd /c start %s", fileName) 
    // etc. 
}