windows 从 Java 运行 Echo
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2684985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
running Echo from Java
提问by ripper234
I'm trying out the Runtime.exec() method to run a command line process.
我正在尝试 Runtime.exec() 方法来运行命令行进程。
I wrote this sample code, which runs without problems but doesn't produce a file at c:\tmp.txt.
我写了这个示例代码,它运行没有问题,但不会在 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
INFO 21-04 20:02:03,024 - Ran 命令“echo foo > c:\tmp.txt”,得到退出代码 0,输出:foo > c:\tmp.txt
回答by Thorbj?rn Ravn Andersen
echo is not a standalone command under Windows, but embedded in cmd.exe.
echo 不是 Windows 下的独立命令,而是嵌入在 cmd.exe 中。
I believe you need to invoke a command like "cmd.exe /C echo ...".
我相信您需要调用像“cmd.exe /C echo ...”这样的命令。
回答by OscarRyz
The >
is intrepreted by the shell, when echo
is run in the cmmand line, and it's the shell who create the file.
该>
是由外壳,当intrepretedecho
在cmmand线运行,这是谁创建该文件的外壳。
When you use it from Java, there is no shell, and what the command sees as argument is :
当您从 Java 使用它时,没有外壳,命令视为参数的是:
"foo > c:\tmp.txt"
"foo > c:\tmp.txt"
( Which you can confirm, from the execution output )
(您可以从执行输出中确认)
回答by Jay
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())."
您不能将 "> c:\tmp.txt" 作为命令行的一部分传递给 Runtime.exec 来进行重定向。来自 Javadocs:“其所有标准 io(即 stdin、stdout、stderr)操作将通过三个流(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.
如果要将输出重定向到文件,据我所知,唯一的方法是用 Java 打开文件,执行 getInputStream,然后从进程的输入流中读取并写入所需的文件。