android 执行shell命令工具类

sancaiodm Android源码摘录 2021-12-25 1718 0

话不多说,直接上代码,可以直接复制使用

public class ShellUtils {
    public static class ShellResult {
        public int result;
        public String successMsg;
        public String errorMsg;

        public ShellResult(int result) {
            this.result = result;
        }

        public ShellResult(int result, String successMsg, String errorMsg) {
            this.result = result;
            this.successMsg = successMsg;
            this.errorMsg = errorMsg;
        }
    }

    public static CmdResult exec(String cmd) {
        int result = -1;
        Process proc = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = null;
        StringBuilder errorMsg = null;
        Runtime runtime = Runtime.getRuntime();
        try {
            proc = runtime.exec(cmd);
            result = proc.waitFor();
            successMsg = new StringBuilder();
            errorMsg = new StringBuilder();
            successResult = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                 android.util.Log.i("shoujidom","successResult:" + s);
                successMsg.append(s);
            }
            while ((s = errorResult.readLine()) != null) {
                android.util.Log.i("shoujidom","errorResult:" + s);
                errorMsg.append(s);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (proc != null) {
                proc.destroy();
            }
        }
        return new ShellResult(result, successMsg == null ? null : successMsg.toString(), errorMsg == null ? null: errorMsg.toString());
    }
}


评论