以编程方式在Android中运行命令管道

时间:2018-12-06 02:41:42

标签: android command pipe

我正在尝试以编程方式在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,而只是转储整个文件。

如何使管道运行?

1 个答案:

答案 0 :(得分:0)

我最终使用了以下代码

String[] cmd = {
  "/system/bin/sh",
  "-c",
  myCmd
};
process = Runtime.getRuntime().exec(cmd);