'How do I read the last line in the console output?

So im trying to make a Java program that uses adb and fastboot to root my Nexus 6P. I have a class that can run the commands, but I need to capture the device ID from the output. when I run adb or fastboot the output either looks like one of the three options below

List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
5VT7N16324000434          device

or

List of devices attached
5VT7N16324000434          device

or

5VT7N16324000434          device

Now I need to capture the 5VT7N16324000434 and save it to a string. Though it will not always be the same. I have searched for hours with nothing helpful, and have no idea where to even start.

I run adb with this class

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ExecuteShellCommand {

public static void main(String inputCommand) {

    ExecuteShellCommand obj = new ExecuteShellCommand();

    String command = inputCommand;

    String output = obj.executeCommand(command);

    System.out.println(output);

}

private String executeCommand(String command) {

    StringBuffer output = new StringBuffer();

    Process p;
    try {
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        BufferedReader reader =
                new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = "";
        while ((line = reader.readLine())!= null) {
            output.append(line + "\n");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return output.toString();

}

}

I then need to read the out put for 5VT7N16324000434 or any string that could be in that place.



Solution 1:[1]

I'm not sure but the only solution that come's up to my mind, is to route the PrintStream (System.out) and assign every line that gets printed to a String called lastLine or something. You can then get the device ID using a regex expression that removes the spaces/tabs after the actual device ID
like this -> (DEVICEID device) to (DEVICEID) or just replace every space using String.replaceAll(" ", ""); and the "device" word using String.replace("device", "");. I hope I could help you, as I'm fairly new to this community.

Edit:
Here's the code that assigns the last line to a String:


private String lastLine;

public void construct() {
    System.setOut(new PrintStream(System.out) {
        public void println(String s) {
            lastLine = s;
            super.println(s);
        }
    });
}

PS: Sorry for my bad English

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1