从 Java 运行 Echo
我正在尝试 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));
输出是
INFO 21-04 20:02:03,024 - Ran 命令 '回声富> c:\tmp.txt',获得退出代码 0、输出:foo> c:\tmp.txt
I'm trying out the Runtime.exec() method to run a command line process.
I wrote this sample code, which runs without problems but doesn't produce a file at 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));
The output is
INFO 21-04 20:02:03,024 - Ran command
'echo foo > c:\tmp.txt', got exit code
0, output: foo > c:\tmp.txt
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
echo 不是 Windows 下的独立命令,而是嵌入在 cmd.exe 中。
我相信您需要调用“cmd.exe /C echo ...”之类的命令。
echo is not a standalone command under Windows, but embedded in cmd.exe.
I believe you need to invoke a command like "cmd.exe /C echo ...".
当在命令行中运行
echo
时,>
由 shell 解释,并且由 shell 创建该文件。当您从 Java 使用它时,没有 shell,命令看到的参数是:
"foo > c:\tmp.txt"
(您可以从执行输出中确认)
The
>
is intrepreted by the shell, whenecho
is run in the cmmand line, and it's the shell who create the file.When you use it from Java, there is no shell, and what the command sees as argument is :
"foo > c:\tmp.txt"
( Which you can confirm, from the execution output )
您不能仅将“> c:\tmp.txt”作为命令行的一部分传递给 Runtime.exec 来实现重定向。来自 Javadocs:“其所有标准 io(即 stdin、stdout、stderr)操作都将通过三个流(getOutputStream()、getInputStream()、getErrorStream())重定向到父进程。”
如果您想将输出重定向到文件,据我所知,唯一的方法是用 Java 打开该文件,执行 getInputStream,然后从进程的输入流中读取并写入所需的文件。
You can't just pass "> c:\tmp.txt" to Runtime.exec as part of the command line to make redirection happen. From the Javadocs: "All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (getOutputStream(), getInputStream(), getErrorStream())."
If you want to redirect output to a file, to the best of my knowledge the only way to do that would be to open the file in Java, do getInputStream, and then read from the process's input stream and write to the desired file.