exec shell command with ProcessBuilder - Android Android OS

Android examples for Android OS:Shell Command

Description

exec shell command with ProcessBuilder

Demo Code


//package com.java2s;

import android.util.AndroidRuntimeException;

import java.io.File;
import java.io.OutputStream;

public class Main {
    static int exec(String shell, String... cmds) {
        try {/* w w w. ja  va 2  s .c o m*/
            ProcessBuilder builder = new ProcessBuilder().command(shell)
                    .redirectErrorStream(true).directory(new File("/"));
            OutputStream stdIn = builder.start().getOutputStream();
            for (String cmd : cmds) {
                if (!cmd.endsWith("\n")) {
                    cmd += "\n";
                }
                stdIn.write(cmd.getBytes());
                stdIn.flush();
            }
            return 0;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new AndroidRuntimeException(e);
        }
    }
}

Related Tutorials