public class shell { static void shell(String sh) throws Exception { try{ Process su = Runtime.getRuntime().exec("su"); DataOutputStream outputStream = new DataOutputStream(su.getOutputStream()); outputStream.writeBytes(sh+"\n"); outputStream.flush(); outputStream.writeBytes("exit\n"); outputStream.flush(); su.waitFor(); }catch(IOException e){ throw new Exception(e); }catch(InterruptedException e){ throw new Exception(e); } } static void shell(String[] sh) throws Exception { try{ Process su = Runtime.getRuntime().exec("su"); DataOutputStream outputStream = new DataOutputStream(su.getOutputStream()); for(String str : sh){ outputStream.writeBytes(str+"\n"); } outputStream.flush(); outputStream.writeBytes("exit\n"); outputStream.flush(); su.waitFor(); }catch(IOException e){ throw new Exception(e); }catch(InterruptedException e){ throw new Exception(e); } } }
//调用: try { shell.shell(new String[]{"echo hello","echo world"});
shell.shell("echo 'hello world'");
} catch (Exception e) { e.printStackTrace(); }
标签:Exception,outputStream,su,shell,catch,new,android,root From: https://www.cnblogs.com/laremehpe/p/16635669.html