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.
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.
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.
Do you think it is the case? Is there a better way to do it? If not, how can I delay Runtime.exec() accordingly?