【问题标题】:Run command pipeline in Android programmatically以编程方式在 Android 中运行命令管道
【发布时间】: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,而是简单地转储整个文件。

如何让管道运行?

【问题讨论】:

    标签: android command pipe


    【解决方案1】:

    我最终使用了以下代码

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-21
      • 2011-03-21
      • 2013-01-26
      • 2013-08-14
      • 2012-04-25
      • 1970-01-01
      • 1970-01-01
      • 2014-10-27
      相关资源
      最近更新 更多