Question

I see the below code in my application to read from buffered reader by limiting the amount of data being read.

public static String readBuffer(Reader reader, int limit) throws IOException 
{           
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < limit; i++) {
        int c = reader.read();
            if (c == -1) {
                return ((sb.length() > 0) ? sb.toString() : null);
            }
        if (((char) c == '\n') || ((char) c == '\r')) {
            break;
    }
        sb.append((char) c);
}
    return sb.toString();
}

Can someone please explain to me what these lines in the code indicate? Why do we need it?

if (((char) c == '\n') || ((char) c == '\r')) {
            break;
    }
Was it helpful?

Solution 2

They mean what they say: If c is a newline (\n) or carriage return (\r) then break out of the loop. (A list of escape sequences in Java can be found here, or if you prefer something more official, JLS section 3.10.6.)

On a higher level; it means this method will process data until either a) a line-ending is hit, or b) the limit is reached (i < limit condition in loop), whichever happens first.

As for why you need it: That's because presumably, one of the design requirements for that method was to have it stop at a line-ending, and that if statement is the way that requirement was implemented.

OTHER TIPS

\n - New Line
\r - Return (Enter)
\n \r \f \t \v     Newline, carriage return, form feed, tab, vertical tab

Refer here and here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top