关于java:读取命令的实时输出

Read realtime output of a command

如何从 Java 读取 shell 命令的实时输出

这是我目前所拥有的,但它在命令执行后打印:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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());
}