我有以下Windows批处理文件(run.bat):
@echo off
echo hello batch file to sysout
以下java代码,它运行批处理文件并将输出重定向到文件:
public static void main(String[] args) throws IOException {
System.out.println("Current java version is: " + System.getProperty("java.version"));
ProcessBuilder pb =
new ProcessBuilder("cmd.exe", "/c",
"run.bat"
,">>", "stdout.txt","2>>", "stderr.txt"
);
System.out.println("Command is: " + pb.command());
Process proc = pb.start();
InputStream in = proc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitValue = proc.exitValue();
System.out.println("Exit value: " + exitValue);
}
在JDK上,包括JDK6u43,我得到以下输出:
Current java version is: 1.6.0_29
Command is: [cmd.exe, /c, run.bat, >>, stdout.txt, 2>>, stderr.txt]
Exit value: 0
并将脚本输出写入文件。 从JDK 6u45和7开始,我得到以下输出:
Current java version is: 1.6.0_45
Command is: [cmd.exe, /c, run.bat, >>, stdout.txt, 2>>, stderr.txt]
hello batch file to sysout
Exit value: 0
没有任何内容写入输出文件。
这可能与Runtime.exec()中所做的更改有关,也可能没有,详见:http://www.oracle.com/technetwork/java/javase/6u45-relnotes-1932876.html
在Windows上使用重定向到文件的输出启动进程的正确方法是什么?
注意:在实际场景中,要执行的命令可能包含带空格的参数,如:
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c",
"run.bat", "Some Input With Spaces",
">>", "stdout.txt","2>>", "stderr.txt");
答案 0 :(得分:9)
这是我在http://tamanmohamed.blogspot.in/2012/06/jdk7-processbuilder-and-how-redirecting.html
上找到的最简单的方法File output = new File("C:/PBExample/ProcessLog.txt");
ProcessBuilder pb = new ProcessBuilder("cmd");
pb.redirectOutput(output);
答案 1 :(得分:3)
这里有几点建议:
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c",
"run.bat", "\"Some Input With Spaces\"",
">>", "stdout.txt","2>>", "stderr.txt");
InputStream stdout = new BufferedInputStream(proc.getInputStream());
FileOutputStream stdoutFile = new FileOutputStream("stdout.txt");
ByteStreams.copy(stdout, stdoutFile);
InputStream stderr = new BufferedInputStream(proc.getErrorStream());
FileOutputStream stderrFile = new FileOutputStream("stderr.txt");
ByteStreams.copy(stderr, stderrFile);
stdout.close();
stderr.close();
stdoutFile.close();
stderrFile.close();
run.bat
包装器?
@echo off
cmd.exe /c run.bat "%1" >> "%2" 2>> "%3"
答案 2 :(得分:0)
在流程上使用getOutputStream()
,而不是使用System.out.println()
。有时语义在Java实现之间会发生变化。
这实际上似乎是一个错误修正 - 较新的实现是有道理的。