exec Shell Command with Runtime.getRuntime().exec() - Android Android OS

Android examples for Android OS:Shell Command

Description

exec Shell Command with Runtime.getRuntime().exec()

Demo Code


//package com.java2s;

import java.io.BufferedReader;

import java.io.DataOutputStream;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import java.util.List;

public class Main {
    public static String execShell(String cmd) {
        String result = null;/*from  w  ww .  j a  v a2  s .com*/
        try {
            Process p = Runtime.getRuntime().exec("su");
            OutputStream outputStream = p.getOutputStream();

            DataOutputStream dataOutputStream = new DataOutputStream(
                    outputStream);
            dataOutputStream.writeBytes(cmd);
            dataOutputStream.flush();
            dataOutputStream.close();
            outputStream.close();

            InputStream inputStream = p.getInputStream();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputStream));
            String line = null;
            while ((line = reader.readLine()) != null) {
                result += line;
            }
            inputStream.close();
            return reader.readLine();
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return result;
    }

   
}

Related Tutorials