Android examples for Android OS:Process
Executes the command and its arguments in a native process.
import java.io.InputStream; import java.util.Scanner; public class Main { private static boolean DEBUG = System.getProperty("cts.vm-tests.debug") != null; /**//ww w. j a va2s. c o m * Executes the command and its arguments in a native process. * * @param commandAndArgs * a string array to be passed containing the executable and its * arguments * @param okIndicator * if not null, this String must occur in the stdout of the executable * (since only checking for the return code is not sufficient e.g. for * adb shell cmd) * @throws Exception * thrown by the underlying command in case of an error. */ public static void digestCommand(String[] commandAndArgs, String okIndicator) { RuntimeException re = null; try { String c = ""; for (int i = 0; i < commandAndArgs.length; i++) { c += commandAndArgs[i] + " "; } if (DEBUG) System.out.print("com: " + c); StringBuilder sb = new StringBuilder(); ProcessBuilder pb = new ProcessBuilder(commandAndArgs).redirectErrorStream(true); Process p = pb.start(); InputStream is = p.getInputStream(); Scanner scanner = new Scanner(is); int retCode = p.waitFor(); while (scanner.hasNextLine()) { sb.append(scanner.nextLine()); } scanner.close(); if (retCode != 0 || (okIndicator != null && !sb.toString().contains(okIndicator))) { String msg = sb.toString() + "\nreturn code: " + retCode; re = new RuntimeException(msg); if (DEBUG) System.out.println("-> error! msg:" + msg); } else { if (DEBUG) System.out.println(" -> " + retCode); } } catch (Exception e) { throw new RuntimeException("Exception occurred: " + e.getClass().getName() + ", msg:" + e.getMessage()); } finally { if (re != null) { throw re; } } } }