[ACCEPTED]-Can BufferedReader (Java) read next line without moving the pointer?-java

Accepted answer
Score: 50

You can use mark() and reset() to mark a spot in the 1 stream and then return to it. Example:

int BUFFER_SIZE = 1000;

buf.mark(BUFFER_SIZE);
buf.readLine();  // returns the GET
buf.readLine();  // returns the Host header
buf.reset();     // rewinds the stream back to the mark
buf.readLine();  // returns the GET again
Score: 19

Just read both current and next line in 1 the loop.

BufferedReader reader = null;
try {
    reader = new BufferedReader(new InputStreamReader(file, encoding));
    for (String next, line = reader.readLine(); line != null; line = next) {
        next = reader.readLine();

        System.out.println("Current line: " + line);
        System.out.println("Next line: " + next);
    }
} finally {
    if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}

More Related questions