我的程序成功创建并填充了一个 Excel(.xls) 文件。创建后,我希望新文件在系统的默认程序中打开(在我的例子中是 Excel)。我怎样才能做到这一点?
对于我想在记事本中打开 txt 文件的旧程序,我使用了以下内容:
if (!Desktop.isDesktopSupported()) {
System.err.println("Desktop not supported");
// use alternative (Runtime.exec)
return;
}
Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.EDIT)) {
System.err.println("EDIT not supported");
// use alternative (Runtime.exec)
return;
}
try {
desktop.edit(new File(this.outputFilePath));
} catch (IOException ex) {
ex.printStackTrace();
}
当我尝试将此代码用于 Excel 文件时,出现以下错误:
java.io.IOException: Failed to edit file:C:/foo.xls
建议?
最佳答案
尝试使用 Desktop.open() 而不是 Desktop.edit() :
Desktop dt = Desktop.getDesktop();
dt.open(new File(this.outputFilePath));
如果 Desktop.open() 不可用,则可以使用 Windows 文件关联:
Process p =
Runtime.getRuntime()
.exec("rundll32 url.dll,FileProtocolHandler " + this.outputFilePath);
关于java - 使用默认程序打开 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2114318/