4

如何从 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());
}
4

1 回答 1

5

尝试这个:

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());
}
于 2014-02-14T08:26:47.550 回答