通过使用start,您要求cmd.exe在后台启动批处理文件:
Process p = Runtime.getRuntime().exec('cmd /c start ' + path + 'RunFromCode.bat');
因此,您从Java(cmd.exe)启动的进程将在后台进程完成之前返回。
删除start命令以在前台运行批处理文件-然后,waitFor()将等待批处理文件完成:
Process p = Runtime.getRuntime().exec('cmd /c ' + path + 'RunFromCode.bat');
根据OP,重要的是要有可用的控制台窗口-这可以通过添加/wait参数来完成,如@Noofiz所建议。以下SSCCE为我工作:
public class Command {public static void main(String[] args) throws java.io.IOException, InterruptedException { String path = 'C:Usersandreas'; Process p = Runtime.getRuntime().exec('cmd /c start /wait ' + path + 'RunFromCode.bat'); Sy@R_301_6051@.out.println('Waiting for batch file ...'); p.waitFor(); Sy@R_301_6051@.out.println('Batch file done.'); }}
如果RunFromCode.bat执行EXIT命令,命令窗口将自动关闭。否则,命令窗口将保持打开状态,直到您使用显式退出它EXIT为止-Java进程一直在等待,直到在两种情况下都关闭了窗口。
解决方法我有这个代码:
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();
发生的是该文件在实际执行之前已删除。
这是因为.bat文件仅包含本机系统调用吗?执行文件 后 如何删除.bat?(我不知道.bat文件的输出是什么,因为它是动态变化的)。