Java proc.waitfor() is being ignored on mac
i ve written a simple program to run on a mac, the program opens an excel file and waits for the the user to close the file after which a simple output is given. when i run the program, excel opens, the proc.wa开发者_JS百科itfor is ignored and it just skips to the output without waiting, any help thanks
Thread myThread = new Thread() {
@Override
public void run() {
try {
String userDir = (System.getProperty("user.home"));
String fileName = userDir + "/Desktop/test/testfile.xlsx";
File theFile = new File(fileName);
Process proc = new ProcessBuilder("/usr/bin/open", fileName).start();
int waitFor = proc.waitFor();
} catch (InterruptedException ex) {
Logger.getLogger(MacTester.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MacTester.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
myThread.start();
System.out.println("excel is now closed");
This line:
System.out.println("excel is now closed");
Should be inside the run method. Your main thread, the thread that is starting your other thread continues with the execution after start has been invoked.
Another alternative is to place:
myThread.join();
on the line after:
myThread.start();
/usr/bin/open
doesn't run modally, it returns the control after launching the appropriate application. You should use open -W
. Consider using open -W -n
which opens the file in a new instance of the application. Consult man open
and try in terminal before testing your java code.
You're doing your process (appropriately) in a background thread, and so what effect will waitfor have on the completely separate calling thread? Answer: none. The solution I see has been given in the other answer -- +1 to him. :)
精彩评论