Run cat command in Android

I want to merge two files in android. I did this from the Terminal Emulator application using the command cat file1 file2 > output_file. But this does not work when I try to execute it from my 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 gave permission to write to external storage in the manifest. What am I missing?

+3
source share
1 answer

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

You can simply add files through 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();
}

In your case, call it twice for file1and file2.

+1

All Articles