【发布时间】:2019-05-07 16:51:40
【问题描述】:
我正在尝试以编程方式在 Android 中运行命令,有些命令包括管道。我正在使用以下代码:
try {
// Executes the command.
Process process = Runtime.getRuntime().exec(command);
// Reads stdout.
// NOTE: You can write to stdin of the command using
// process.getOutputStream().
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
// Waits for the command to finish.
process.waitFor();
return output.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
这适用于普通命令,但当命令是管道时,例如“cat some-multi-line-file.txt | grep some-search-parameter”,它无法运行 grep,而是简单地转储整个文件。
如何让管道运行?
【问题讨论】: