Search code examples
javajava-iostringreader

Using StringReader to read to the end of String


How can I use a StringReader in Java to read to the end of a string, where I don't know what the length of the string will be.

This is how far I've gotten so far:

public static boolean portForward(Device dev, int localPort, int remotePort)
{
    boolean success = false;
    AdbCommand adbCmd = Adb.formAdbCommand(dev, "forward", "tcp:" + localPort, "tcp:" + remotePort);
    StringReader reader = new StringReader(executeAdbCommand(adbCmd));
    try
    {
        if (/*This is what's missing :/ */)
        {
            success = true;
        }
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "There was an error while retrieving the list of devices.\n" + ex + "\nPlease report this error to the developer/s.", "Error Retrieving Devices", JOptionPane.ERROR_MESSAGE);
    } finally {
        reader.close();
    }

    return success;
}

Solution

  • Based on the comment to your question, where you basically say that you just want to verify that the string is empty.

    if (reader.read() == -1)
    {
       // There is nothing in the stream, way to go!!
       success = true;
    }
    

    or, even simpler:

    String result = executeAdbCommand(adbCmd);
    success = result.length() == 0;