I have this code:
File file = new File(path + "\\RunFromCode.bat");
file.createNewFile();
PrintWriter writer = new PrintWriter(file, "UTF-8");
for (int i = 0; i <= MAX; i++) {
writer.println("@cd " + i);
writer.println(NATIVE SYSTEM COMMANDS);
// more things
}
writer.close();
Process p = Runtime.getRuntime().exec("cmd /c start " + path + "\\RunFromCode.bat");
p.waitFor();
file.delete();
What happens is that the file deleted before it actually executed.
Is this because the .bat
file contains only native system call? How can I make the deletion after the execution of the .bat
file? (I don't know what the output of the .bat
file will be, since it dynamically changes).
By using start
, you are askingcmd.exe
to start the batch file in the background:
Process p = Runtime.getRuntime().exec("cmd /c start " + path + "\\RunFromCode.bat");
So, the process which you launch from Java (cmd.exe
) returns before the background process is finished.
Remove the start
command to run the batch file in the foreground - then, waitFor()
will wait for the batch file completion:
Process p = Runtime.getRuntime().exec("cmd /c " + path + "\\RunFromCode.bat");
According to OP, it is important to have the console window available - this can be done by adding the /wait
parameter, as suggested by @Noofiz. The following SSCCE worked for me:
public class Command {
public static void main(String[] args) throws java.io.IOException, InterruptedException {
String path = "C:\\Users\\andreas";
Process p = Runtime.getRuntime().exec("cmd /c start /wait " + path + "\\RunFromCode.bat");
System.out.println("Waiting for batch file ...");
p.waitFor();
System.out.println("Batch file done.");
}
}
If RunFromCode.bat
executes the EXIT
command, the command window is automatically closed. Otherwise, the command window remains open until you explicitly exit it with EXIT
- the java process is waiting until the window is closed in either case.
Try adding /wait
parameter in front of the start
command.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With