Reputation: 1596
I have written a simple java program to invoke a batch file. The problem is, when I'm running this Java program nothing happens, the batch file is not executed. But when I execute the same program in debug mode going line by line, then the batch file gets executed.
The problem I'm suspecting here is my JVM is getting shutdown before my process actually finishes. I can put in Thread.sleep() but I don't want to do it. Is there any other way so that my process is completed and then JVM is shutdown.
public static void main(String[] args) {
String batchFilePath = "D:\\MyDir";
String batchFileName = "callMe.bat";
executeBatchFile(batchFilePath, batchFileName);
}
public static void executeBatchFile(String filePath, String fileName) {
try {
List cmdAndArgs = Arrays.asList("cmd", "/c", fileName);
ProcessBuilder pb = new ProcessBuilder(cmdAndArgs);
pb.directory(new File(filePath));
Process p = pb.start();
} catch (Exception e) {
e.printStackTrace();
}
Upvotes: 1
Views: 67
Reputation: 68715
You can use waitFor method of ProcessBuilder to wait for the launched process to finish. Here is the description of waitFor
from javadocs
Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.
Upvotes: 2