我有以下 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);
}
在 JDK6u43 及以下的 JDK 上,我得到以下输出:
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");