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

当您不知道文件与哪个应用程序相关联时,如何从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) 。 特别是, Desktop类具有您正在寻找的方法。

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