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

Mer*_*ous 17 java external-application

当您不知道文件与哪个应用程序相关联时,如何从Java应用程序中打开文件.另外,因为我使用Java,所以我更喜欢独立于平台的解决方案.

Rea*_*wTo 40

使用JDK1.6,java.awt.Desktop该类可能很有用.

public static void open(File document) throws IOException {
    Desktop dt = Desktop.getDesktop();
    dt.open(document);
}
Run Code Online (Sandbox Code Playgroud)


Osc*_*Ryz 5

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

自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. 
}
Run Code Online (Sandbox Code Playgroud)