I need to open an excel file, test something with it, and then close said excel file within a Java application. I am on a Mac, and I have tried the following ways to do this but I was unsuccessful.
I tried to use the java AWT Desktop (java.awt.Desktop) class, like this:
//excel is selected by the OS as the default application to open this file
Desktop.getDesktop().open(new File(excelFile.getAbsolutePath()));
This works to open the file, process the file, and it looks like it works with a standard QuitHandler
which would exit on System.exit(0)
. I can create a custom QuitHandler, but what is confusing me is how can I dispatch a message to the Desktop to let it know that it needs to quit.
The docs for Desktop says
The handler is passed a one-shot {@link java.awt.desktop.QuitResponse} which can cancel or proceed with the quit.
If I check the Docs for handleQuitRequestWith
within QuitResponse
, I see
Implementors must call either {@link QuitResponse#cancelQuit()}, {@link QuitResponse#performQuit()}, or ensure the application terminates. The process (or log-out) requesting this app to quit will be blocked until the {@link QuitResponse} is handled.
The method signature looks like public void handleQuitRequestWith(QuitEvent e, QuitResponse response);
.
What I am confused in is how can I use this in order to let the desktop application know to quit? Is there a way to dispatch a message to make it quit?
I have also tried to execute a command through the Runtime class like this:
Process excelProcess = Runtime.getRuntime().exec("open " + excelFile.getAbsolutePath());
This would give me a Process
to reference, and I can call the destroy
method when I didn’t need it anymore, but the problem that I had with this approach was that the file would not open. I executed the raw command from exec
in my terminal, and the file opened in excel without any issues. I’m not a huge fan of this approach because it seems a bit kludgy, but I wanted to call it out that I tried this approach. Ideally, I would like to be able to use the Desktop API if possible.