Java – Read the real-time output of the command

Read the real-time output of the command… here is a solution to the problem.

Read the real-time output of the command

How to read the real-time output of shell commands from Java

This is what I have at the moment, but it prints after executing the command :

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());
}

Solution

Try this :

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());
}

Related Problems and Solutions