简体   繁体   中英

Can BufferedReader (Java) read next line without moving the pointer?


I am trying to read next next line without moving the pointer, is that possible?

BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));

while ((readString = buf.readLine()) != null) {
}

the While will read line by line as i want, but i need to write the next line of the current line.

it is possible?

my file contain Http request data, the first line is the GET request,
in the second line the Host name, i need to pull out the Host before the GET to be able to connect it together.
Host/+the GET url,

GET /logos/2011/family10-hp.jpg HTTP/1.1  
Host: www.google.com  
Accept-Encoding: gzip  

Thanks.

You can use mark() and reset() to mark a spot in the 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

Just read both current and next line in 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) {}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM