主批处理文件调用或启动其他批处理文件。通过java processbuilder调用主批处理文件。获取了主文件“调用”的批处理文件的日志,但无法获取“启动”的批处理文件的日志,因为它们是在新的cmd窗口中打开的。
主.bat
echo Hello World From main.bat
call first.bat
start second.bat
第一棒
echo Hello World From first.bat
第二棒
echo Hello World From second.bat
本例中的job.getscript()是“cd path\to\parent\folder\n main.bat”
运行作业
public void runJob(Job job) throws InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe");
Process process = null;
try {
process = processBuilder.start();
} catch (IOException e1) {
e1.printStackTrace();
}
BufferedWriter process_stdin = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
for(String command : job.getScript().split("\n")) {
executeCommand(command, process_stdin);
}
executeCommand("exit", process_stdin);
process_stdin.close();
//Logs
final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringJoiner sj = new StringJoiner(System.getProperty("line.separator"));
reader.lines().iterator().forEachRemaining(sj::add);
System.out.println(sj.toString())
}
执行命令
private void executeCommand(String command, BufferedWriter process_stdin) {
try {
// single execution
process_stdin.write(command);
process_stdin.newLine();
process_stdin.flush();
} catch (IOException e) {
System.out.println(e);
}
}
日志
C:\>cd path\\to\\parent\\folder
path\\to\\parent\\folder>main.bat
path\\to\\parent\\folder>echo Hello World From main.bat
Hello World From main.bat
path\\to\\parent\\folder>call first.bat
path\\to\\parent\\folder>echo Hello World From first.bat
Hello World From first.bat
path\\to\\parent\\folder>start second.bat
path\\to\\parent\\folder>exit
暂无答案!
目前还没有任何答案,快来回答吧!