在Android中运行cat命令

时间:2011-10-14 11:02:22

标签: android command-line terminal exec

我想在android中连接两个文件。我使用命令cat file1 file2 > output_file从终端仿真器应用程序执行此操作。但是当我尝试从我的代码执行它时,它不起作用。

这是我用来执行命令的代码。

    public String exec() {
    try {

        // Executes the command.
        String CAT_COMMAND = "/system/bin/cat /sdcard/file1 /sdcard/file2 > /sdcard/output_file";
        Process process = Runtime.getRuntime().exec(CAT_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);
    }
}

我已经允许写入清单中的外部存储空间。我错过了什么?

1 个答案:

答案 0 :(得分:1)

如评论中所述,您需要一个shell来执行流程输出重定向(通过>)。

您只需通过以下代码附加文件:

void append(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src, true);  // `true` means append 
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
       out.write(buf, 0, len);
    }
    in.close();
    out.close();
}

在您的情况下,请为file1file2调用两次。