【发布时间】:2016-05-16 21:04:26
【问题描述】:
我正在尝试使用 java 在 shell 中执行重定向,但我得到一个空的 file1.txt 命令:ls -all > file1.txt。
虽然ls -all被正确执行了。
commandLine 是字符串类型,并且具有我想要执行的命令。
例如String commandLine = "ls -all";
代码片段(这是代码的相关部分):
StringBuilder output = new StringBuilder();
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(new String[]{"/bin/sh", "-c", commandLine});
process.waitFor();
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
line = "";
while ((line = reader.readLine())!= null) {
output.append(line);
output.append("\n");
}
}
catch(Exception ex) {
ex.printStackTrace();
}
finally {
process.destroy();
}
最后,我正在处理来自实例 output 的输出。
另外,我想执行类似于curl -v http://www.centos.org > /dev/null 的命令,但这也给了我一个空的响应!
【问题讨论】:
-
commandLine是什么? -
哎呀忘了提。我已经编辑了我的问题以包括 commandLine 是什么!感谢您提出这个问题!
-
> /dev/null 显然会给你一个空的响应,因为这就是人们重定向到 /dev/null 的原因
-
但是在 bash 上运行相同的命令会给我一个输出。我应该用什么代替 /dev/null 来获得输出?还有,为什么file1.txt是空的
-
你的意思可能是一个错误?不要将 stdout 与 stderr 混合使用!
标签: java shell ubuntu io-redirection