读取命令的实时输出

时间:2012-11-23 13:49:19

标签: java android

如何从Java

中读取shell命令的实时输出

这是我到目前为止所做的,但它在执行命令后打印:

try {
    proc = Runtime.getRuntime().exec("du -d 1 /sdcard/");

    InputStream inputStream = proc.getInputStream();
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

    while ((line = bufferedReader.readLine()) != null) {
        publishProgress(i);
        i++;
        System.out.println(line); // it prints all at once after command has been executed.
    }
}
catch (IOException e) {
    Log.e("du","error "+e.getMessage());
}

1 个答案:

答案 0 :(得分:4)

试试这个:

try {
 proc = Runtime.getRuntime().exec("du -d 1 /sdcard/");

 InputStream inputStream = proc.getInputStream();
 InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
 BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

 while ((line = bufferedReader.readLine()) != null) {
    System.out.println(line); // it prints all at once after command has been executed.
 }
 proc.waitFor();
}
catch (IOException e) {
 Log.e("du","error "+e.getMessage());
}