在Android上运行cat命令 [英] Run cat command in Android

查看:767
本文介绍了在Android上运行cat命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想连接android系统中的两个文件。我这样做是使用命令猫文件1文件2&GT终端仿真器应用程序; OUTPUT_FILE 。但是,当我尝试从我的code执行它不起作用。

I want to concatenate two files in android. I did this from the Terminal Emulator app using the command cat file1 file2 > output_file. But it does not work when I try to execute it from my code.

这是code,我用要执行的命令。

This is the code that I used to execute the command.

    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);
    }
}

我给写在清单外部存储的权限。我缺少什么?

I have given the permission to write to external storage in the manifest. What am I missing?

推荐答案

正如评论指出的那样,你需要一个壳里做过程输出重定向(通过>

As noted in comment, you need a shell to do process output redirect (via the >).

您可以只需通过这个code附加文件:

You can simply append files via this code:

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();
}

在您的情况下把它叫做两次文件1 文件2

In your case call it twice for file1 and file2.

这篇关于在Android上运行cat命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆