android 执行shell命令工具类
话不多说,直接上代码,可以直接复制使用
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());
}
}版权声明:如无特殊标注,文章均为本站原创,转载时请以链接形式注明文章出处。




评论