在 Java 上使用外部应用程序打开文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/390736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Open a file with an external application on Java
提问by Mercurious
How do you open a file from a java application when you do not know which application the file is associated with. Also, because I'm using Java, I'd prefer a platform independent solution.
当您不知道文件与哪个应用程序关联时,如何从 Java 应用程序打开文件。另外,因为我使用的是 Java,所以我更喜欢独立于平台的解决方案。
采纳答案by RealHowTo
With JDK1.6, the java.awt.Desktop
class can be useful.
对于 JDK1.6,java.awt.Desktop
该类很有用。
public static void open(File document) throws IOException {
Desktop dt = Desktop.getDesktop();
dt.open(document);
}
回答by Dave Ray
You could hack something together with a bat file on Windows and equivalent on Unix, but that wouldn't be that fun.
你可以在 Windows 上用 bat 文件和 Unix 上的等效文件一起破解一些东西,但这不会那么有趣。
I think your best bet would be the JDesktop Integration Components (JDIC). In particular, the Desktopclass has exactly the method you're looking for.
我认为您最好的选择是JDesktop 集成组件 (JDIC)。特别是,Desktop类具有您正在寻找的方法。
EDIT: Apparently, I'm behind the times because this has been integrated into Java 1.6. In any case, if you're working in an earlier Java, it may still be useful.
编辑:显然,我落后于时代,因为它已集成到 Java 1.6 中。无论如何,如果您使用的是较早的 Java,它可能仍然有用。
回答by OscarRyz
File file
Desktop.getDesktop().open( file );
Since Java 1.6
从 Java 1.6 开始
Previous to that you could check this question
在此之前,您可以检查此问题
Summary
概括
It would look something like this:
它看起来像这样:
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.
}