我可以帮助您翻译以下的 Windows 批处理文件(run.bat):
以下是运行批处理文件并将输出重定向到文件的Java代码:
我有以下的 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");
\c
右侧的所有命令行参数组合成单个参数是否有帮助? - David R Tribble