You can do that with:
java.awt.Desktop.getDesktop().edit(file);
This links to the tutorial article on java.awt.Desktop:
Java? Standard Edition version 6
narrows the gap between performance
and integration of native applications
and Java applications. Along with the
new system tray functionality, splash
screen support, and enhanced printing
for JTables , Java SE version 6
provides the Desktop API
(java.awt.Desktop) API, which allows
Java applications to interact with
default applications associated with
specific file types on the host
platform.
It is cross-platform, but may not be supported everywhere. There is a method you can call to check whether the Desktop API is available, called isDesktopSupported (see the link for more explanation). I was using this API the other day to open PDFs in a Swing client.
Unfortunately there is a known bug affecting some Windows platforms (XP and 2003) that will crash the JVM. Write once, debug everywhere, as usual. Anyway, for Windows there is a nice workaround which still uses the user's preferred application:
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
String cmd = "rundll32 url.dll,FileProtocolHandler " + file.getCanonicalPath();
Runtime.getRuntime().exec(cmd);
}
else {
Desktop.getDesktop().edit(file);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…