1 Packagecom.android.utils;2 3 4 ImportJava.io.File;5 6 Importjava.io.IOException;7 ImportJava.io.InputStream;8 Importjava.util.ArrayList;9 Importjava.util.List;Ten One /** A * This class is primarily used to execute Linux shell commands at the Java layer to obtain information under some systems - * The DMESG in this example require some additional permissions to use - * @authorZENGJF the */ - Public classShellExecute { - /** - * This function is used to execute the Linux shell command + * - * @paramCommand shell commands, support pipeline, redirect + * @paramDirectory executes commands under the specified directory A * @returnreturn shell command execution result at * @throwsIOException throws IOException - */ - Public Staticstring Execute (String command, string directory) - throwsIOException { - - //Check the arguments in if(NULL==command) - return""; to + if(Command.trim (). Equals ("")) - return""; the * if(NULL= = Directory | | Directory.trim (). Equals ("")) $directory = "/";Panax Notoginseng -String result = "" ; the +List<string> Cmds =NewArraylist<string>(); ACmds.add ("sh"); theCmds.add ("-C"); + cmds.add (command); - $ Try { $Processbuilder Builder =NewProcessbuilder (CMDS); - - if(Directory! =NULL ) theBuilder.directory (NewFile (directory)); - WuyiBuilder.redirecterrorstream (true) ; theProcess Process =Builder.start (); - Wu //get the result after the command executes -InputStream is =Process.getinputstream (); About byte[] buffer =New byte[1024] ; $ while(Is.read (buffer)! =-1 ) -result = result +NewString (buffer); - - Is.close (); A}Catch(Exception e) { + E.printstacktrace (); the } - returnResult.trim (); $ } the the /** the * This function is used to execute the Linux shell command, the execution directory is specified as: "/" the * - * @paramCommand shell commands, support pipeline, redirect in * @returnreturn shell command execution result the * @throwsIOException throws IOException the */ About Public StaticString execute (String command)throwsIOException { the the //Check the arguments the if(NULL==command) + return""; - the if(Command.trim (). Equals ("")) Bayi return""; the the returnExecute (Command, "/"); - } - the /** the * This function is used to determine if there is a pattern string in DMESG, and the execution directory is specified as: "/" the * the * @paramstring that pattern matches grep - * @returnstrings in pattern are present in TRUE:DMESG <br> the * String in pattern does not exist in FALSE:DMESG the * @throwsIOException throws IOException the */94 Public Static BooleanDeviceexist (String pattern)throwsioexception{ the the //Check the arguments the if(NULL==pattern)98 return false; About - if(Pattern.trim (). Equals ("")) 101 return false;102 103 returnExecute ("DMESG | grep "+ pattern". Length () > 0;104 } the}
Android Shell Command Execute Demo