Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:


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 758
kimo Avatar asked Feb 04 '11 18:02

kimo


People also ask

Does BufferedReader read newline?

BufferedReaderThe readLine() method reads a line of text from the file and returns a string containing the contents of the line, excluding any line-termination characters or null.

Does readLine go to the next line?

readline() returns the next line of the file which contains a newline character in the end. Also, if the end of the file is reached, it will return an empty string.

Which method is used for reading a line of text in BufferedReader?

The readLine() method of BufferedReader class in Java is used to read one line text at a time.

How do you skip a line in buffered reader?

The skip() method of BufferedReader class in Java is used to skip characters in the stream. The number of characters to be skipped is passed as parameter in this method. Overrides: This method overrides skip() method of Reader class.


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 102
ataylor Avatar answered Sep 30 '22 03:09

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 31
BalusC Avatar answered Sep 30 '22 02:09

BalusC