Inside of a Java process, is possible to do the following:
- Invoke Microsoft Word to open a document
- Sleep the Java process until the user finishes editing the document
- When the user "closes" the document in Microsoft Word, restore the Java process and continue executing
I can open Microsoft Word from Java, using the Desktop
or Process
class, but i am not able to wait until Microsoft Words closes. My Java process always continues processing when Microsoft Word is started.
Is it possible to do this without any COM
library?
Attempts that i have done:
1) Invoke winword.exe directly
Process p = Runtime.getRuntime().exec("C:\\Program Files (x86)\\Microsoft Office\\Office14\\WINWORD.EXE \""+FILEPATH+"\"");
p.waitFor();
But if i open another Word document while i am editing the opened document, then winword.exe does not close, so, Java Process does not continue executing and keep waiting. In addition, i must know where is Microsoft Word installed - it is bad idea -
2) Invoke rundll32 and fileprotocolhandler
Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+FILEPATH);
p.waitFor();
File file = new File(FILEPATH);
while(true){
try{
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
FileLock lock = channel.lock();
break;
}catch(Exception e){
Thread.sleep(3*1000);
}
}
When opened, i try to lock the file. If i can lock the file i suppose Microsoft Word is closed. The problem is sometimes this code locks the file before Microsoft Word is opened, p.waitFor() does not work properly.
3) Create a visual basic .exe that opens Word document and when it is closed, then the .exe finish
Process p = Runtime.getRuntime().exec("C:/openWordAndWaitClose.exe "+FILEPATH);
p.waitFor();
This works fine, but... i do not like it very much because there are several technologies for the purpose. In future updates, i do not know if it will work well.