我正在尝试运行Runtime.exec()方法来运行命令行进程.
我编写了这个示例代码,它运行没有问题,但不会在c:\ tmp.txt生成文件.
String cmdLine = "echo foo > c:\\tmp.txt";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(cmdLine);
BufferedReader input = new BufferedReader(
new InputStreamReader(pr.getInputStream()));
String line;
StringBuilder output = new StringBuilder();
while ((line = input.readLine()) != null) {
output.append(line);
}
int exitVal = pr.waitFor();
logger.info(String.format("Ran command '%s', got exit code %d, output:\n%s", cmdLine, exitVal, output));
Run Code Online (Sandbox Code Playgroud)
输出是
INFO 21-04 20:02:03,024 - 执行命令'echo foo> c:\ tmp.txt',退出代码为0,输出:foo> c:\ tmp.txt
echo不是Windows下的独立命令,而是嵌入在cmd.exe中.
我相信你需要调用像"cmd.exe/C echo ..."这样的命令.