droid代碼庫之執行Shell命令或者腳本

http://www.wuphone.com/193


public String execCommand(String command) throws IOException {

// start the ls command running
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command); // 這句話就是shell與高級語言間的調用
// 如果有參數的話可以用另外一個被重載的exec方法

// 實際上這樣執行時啓動了一個子進程,它沒有父進程的控制檯
// 也就看不到輸出,所以我們需要用輸出流來得到shell執行後的輸出
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

// read the ls output

String line = “”;
StringBuilder sb = new StringBuilder(line);
while ((line = bufferedreader.readLine()) != null) {
// System.out.println(line);
sb.append(line);
sb.append(‘\n’);
}

// 使用exec執行不會等執行成功以後才返回,它會立即返回
// 所以在某些情況下是很要命的(比如複製文件的時候)
// 使用wairFor()可以等待命令執行完成以後才返回
try {
if (proc.waitFor() != 0) {
System.err.println(“exit value = ” + proc.exitValue());
}
} catch (InterruptedException e) {
System.err.println(e);
}
return sb.toString();

}
另一段執行Shell的代碼


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章