Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BufferedReader check next lines of a loop before looping

I'm parsing a .cvs file. For each line of the cvs, I create an object with the parsed values, and put them into a set.

Before putting the object in the map and looping to the next, I need to check if the next cvs's line is the same object as the actual, but with a particular property value different.

For that, I need check the next lines of the buffer, but keep the loop's buffer in the same position.

For example:

BufferedReader input  = new BufferedReader(new InputStreamReader(new FileInputStream(file),"ISO-8859-1"));
String line = null;

while ((line = input.readLine()) != null) {
    do something

    while ((nextline = input.readLine()) != null) { //now I have to check the next lines
       //I do something with the next lines. and then break.
    }
    do something else and continue the first loop.
}
like image 547
André Perazzi Avatar asked Feb 08 '12 17:02

André Perazzi


2 Answers

  1. You can mark the current position using BufferedReader.mark(int). To return to the position you call BufferedReader.reset(). The parameter to mark is the "read ahead limit"; if you try to reset() after reading more than the limit you may get an IOException.

  2. Or you could use RandomAccessFile instead:

    // Get current position
    long pos = raf.getFilePointer();
    // read more lines...
    // Return to old position
    raf.seek(pos);
    
  3. Or you could use PushbackReader which allows you to unread characters. But there's the drawback: PushbackReader does not provide a readLine method.

like image 198
Joni Avatar answered Sep 21 '22 00:09

Joni


Consider of using something that is already made like OpenCSV. I think that you could create something like custom mapping strategy for it.

like image 23
Grzegorz Gajos Avatar answered Sep 21 '22 00:09

Grzegorz Gajos