Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;
import java.io.InputStream;

import java.io.DataOutputStream;
import java.io.InputStreamReader;

public class Main {
    public static String RunExecCmd(StringBuilder sb, Boolean su) {

        String shell;
        if (su) {
            shell = "su";
        } else {
            shell = "sh";
        }

        Process process = null;

        DataOutputStream processOutput = null;
        InputStream processInput = null;
        String outmsg = new String();

        try {

            process = Runtime.getRuntime().exec(shell);
            processOutput = new DataOutputStream(process.getOutputStream());
            processOutput.writeBytes(sb.toString() + "\n");
            processOutput.writeBytes("exit\n");
            processOutput.flush();
            processInput = process.getInputStream();
            outmsg = inputStream2String(processInput, "UTF-8");
            process.waitFor();

        } catch (Exception e) {
            //Log.d("*** DEBUG ***", "ROOT REE" + e.getMessage());
            //return;
        }

        finally {
            try {
                if (processOutput != null) {
                    processOutput.close();
                }
                process.destroy();
            } catch (Exception e) {
            }

        }
        return outmsg;
    }

    public static String inputStream2String(InputStream in, String encoding) throws Exception {
        StringBuffer out = new StringBuffer();
        InputStreamReader inread = new InputStreamReader(in, encoding);

        char[] b = new char[4096];
        try {
            for (int n; (n = inread.read(b)) != -1;) {
                out.append(new String(b, 0, n));
            }
        } catch (IOException e) {
        }
        return out.toString();
    }
}