2008-12-24 66 views

回答

40

使用JDK1.6,java.awt.Desktop類可能會有用。

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

這段代碼是否也適用於linux? – 2017-07-23 14:58:42

+0

是的......但最好先調用`Desktop.isDesktopSupported()`或`Desktop.isSupported(action)`,參見Javadoc。 – RealHowTo 2017-07-27 19:55:52

2

你可以用Windows上的bat文件和Unix上的bat文件破解一些東西,但那不會很有趣。

我認爲你最好的選擇是JDesktop Integration Components (JDIC)。特別是,Desktop類具有您正在尋找的方法。

編輯:顯然,我落後於時代,因爲這已經集成到Java 1.6中。無論如何,如果你正在使用早期的Java,它可能仍然有用。

+0

提供的鏈接已損壞。你需要解決這兩個問題。謝謝。 – 2008-12-24 04:39:49

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

由於Java 1.6

此之前,你可以check this question

摘要

這將是這個樣子:

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. 
} 
相關問題