从Java运行Echo

rip*_*234 3 java windows exec

我正在尝试运行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

Tho*_*sen 8

echo不是Windows下的独立命令,而是嵌入在cmd.exe中.

我相信你需要调用像"cmd.exe/C echo ..."这样的命令.

  • 这不是问题,因为退出代码是0(意味着成功),问题是文件重定向(`>`)由shell/cmd.exe处理,因此不应用.然而,解决方案仍然是相同的. (3认同)