在 Java 上使用外部应用程序打开文件[重复]
-
23-08-2019 - |
题
这个问题在这里已经有答案了:
- 如何使用默认关联程序打开文件 3 个回答
当您不知道文件与哪个应用程序关联时,如何从 java 应用程序打开文件。另外,因为我使用的是 Java,所以我更喜欢独立于平台的解决方案。
解决方案
使用 JDK1.6 时, java.awt.Desktop
类可能有用。
public static void open(File document) throws IOException {
Desktop dt = Desktop.getDesktop();
dt.open(document);
}
其他提示
File file
Desktop.getDesktop().open( file );
从 Java 1.6 开始
在此之前你可以 检查这个问题
概括
它看起来像这样:
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.
}
您可以在 Windows 上使用 bat 文件以及在 Unix 上使用同等文件来破解某些内容,但这并不那么有趣。
我认为你最好的选择是 JDesktop 集成组件 (JDIC). 。特别是, 桌面 类正是您正在寻找的方法。
编辑:显然,我落后了时代,因为这已经集成到 Java 1.6 中了。无论如何,如果您使用的是早期的 Java,它可能仍然有用。
不隶属于 StackOverflow