I have written a method that successfully exports data from an array to an Excel file. However, I would like Java to automatically open the freshly created Excel file when Apache POI is done writing it.
我编写了一个成功将数据从数组导出到Excel文件的方法。但是,我希望Java在Apache POI编写完成后自动打开新创建的Excel文件。
My code looks like this:
我的代码如下所示:
public void exportData(Object[][] data, String[] columnNames) {
HSSFWorkbook wb = new HSSFWorkbook();
// Export logic here...
FileOutputStream fileOut = new FileOutputStream(new File(myFilePath));
wb.write(fileOut); // Write the Excel file
fileOut.close(); // Close it
openFile(); // Open it with Excel
}
public void openFile() { // Excel file opening method
try {
Runtime.getRuntime().exec("cmd.exe /c start " + new File(myFilePath));
} catch (Exception e) {
e.printStackTrace();
}
}
It behaves as follows:
它的行为如下:
- When I call exportData() during runtime, the Excel file is written as it should be, but is not automatically opened.
- If I "manually" call openFile() again afterwards (through a JButton ActionEvent, for example), it works.
- If I start my application in NetBeans' debug mode and proceed step by step, it works without needing to manually call openFile() afterwards.
当我在运行时调用exportData()时,Excel文件按原样写入,但不会自动打开。
如果我之后“手动”再次调用openFile()(例如通过JButton ActionEvent),它就可以工作。
如果我在NetBeans的调试模式下启动我的应用程序并逐步进行,则无需手动调用openFile()。
My guess is that something is being done in the background here, and that it takes some time, while my program goes on; therefore, I think my Runtime.exec() may happen before the file is ready to be opened.
我的猜测是这里有一些东西在做,而且需要一些时间,而我的程序还在继续;因此,我认为我的Runtime.exec()可能在文件准备好打开之前发生。
Do you think it is the case? Is there a better way to do it? If not, how can I delay Runtime.exec() accordingly?
你认为是这样的吗?有没有更好的方法呢?如果没有,我如何相应地延迟Runtime.exec()?
1 个解决方案
#1
2
I don't know what is the exact problem that prevents your command from working. But in general, when you want to open a file, it makes sense to use java.awt.Desktop
instead of spawning a process to do so.
我不知道阻止命令工作的确切问题是什么。但一般来说,当你想打开一个文件时,使用java.awt.Desktop而不是生成一个进程是有意义的。
So in your case
所以在你的情况下
Runtime.getRuntime().exec("cmd.exe /c start " + new File(myFilePath));
Becomes
Desktop.getDesktop().open(new File(myFilePath));
AWT takes care of ensuring everything goes smoothly, and you get better cross-platform support this way.
AWT负责确保一切顺利,您可以通过这种方式获得更好的跨平台支持。
#1
2
I don't know what is the exact problem that prevents your command from working. But in general, when you want to open a file, it makes sense to use java.awt.Desktop
instead of spawning a process to do so.
我不知道阻止命令工作的确切问题是什么。但一般来说,当你想打开一个文件时,使用java.awt.Desktop而不是生成一个进程是有意义的。
So in your case
所以在你的情况下
Runtime.getRuntime().exec("cmd.exe /c start " + new File(myFilePath));
Becomes
Desktop.getDesktop().open(new File(myFilePath));
AWT takes care of ensuring everything goes smoothly, and you get better cross-platform support this way.
AWT负责确保一切顺利,您可以通过这种方式获得更好的跨平台支持。