Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the next line in Java without moving the pointer? [duplicate]

Tags:

java


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.

like image 990
kimo Avatar asked Apr 18 '26 03:04

kimo


2 Answers

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
like image 192
ataylor Avatar answered Apr 19 '26 16:04

ataylor


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) {}
}
like image 28
BalusC Avatar answered Apr 19 '26 15:04

BalusC