Open a file with an external application on Java [duplicate]

混江龙づ霸主 提交于 2019-12-29 04:36:09

问题


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.


回答1:


With JDK1.6, the java.awt.Desktop class can be useful.

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



回答2:


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

Since 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. 
}



回答3:


You could hack something together with a bat file on Windows and equivalent on Unix, but that wouldn't be that fun.

I think your best bet would be the JDesktop Integration Components (JDIC). In particular, the Desktop class has exactly the method you're looking for.

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.



来源:https://stackoverflow.com/questions/390736/open-a-file-with-an-external-application-on-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!