I open office files (docx, xlsx) by using Runtime.getRuntime().exec(String cmd) function. Simultaneously I store meta data of these files in a database. In order to keep integrity I lock the file with a flag in the meta data so that no other user concurrently can modify the file. This implies that the flag must be automatically resetted after the user closes the file (e.g. closes the external process).
Here’s the snippet that opens the file:
File file = new File("c:/test.docx");
Process process = null;
if(file.getName().endsWith("docx")) {
process = Runtime.getRuntime().exec("c:/msoffice/WINWORD.EXE "+file.getAbsolutePath());
} else if(file.getName().endsWith("xlsx")) {
process = Runtime.getRuntime().exec("c:/msoffice/EXCEL.EXE "+file.getAbsolutePath());
}
if(process!=null) {
new ProcessExitListener(file, process);
}
Here’s my listener that waits until the user closes the file (and finally unlocks the file by setting the flag in the meta data):
private class ProcessExitListener extends Thread {
private File file;
private Process process;
public ProcessExitListener(File file, Process process) throws IOException {
this.setName("File-Thread ["+process.toString()+"]");
this.file = file;
this.process = process;
this.start();
}
@Override
public void run() {
try {
process.waitFor();
database.unlock(file);
} catch (InterruptedException ex) {
// print exception
}
}
}
This works fine for different file types, e.g. if I open 1 docx and 1 xlsx file simultaneously. But when opening 2 docx files, one of the process exits right after it has been initialized.
Any ideas why ?
Thanks for your help in advance!
Probably because
winword.exeprocess finds out that there is already one instance of it running, so instead of keeping two instances in memory, it just asks the first instance to open the second document. Don’t know how it looks from GUI perspective, but looking at the task manager, try opening two Word documents from Windows Explorer. The second file won’t cause secondwinword.exeprocess to start.I can reproduce the exact same behaviour on Ubuntu Linux. When I ran:
and the geany editor wasn’t yet running, the console hangs until I close the editor. But if instead I open another terminal and call:
this returns immediately and
bar.txtis simply opened as another tab in already existing process.