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.
}
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.
Or you could use RandomAccessFile
instead:
// Get current position
long pos = raf.getFilePointer();
// read more lines...
// Return to old position
raf.seek(pos);
Or you could use PushbackReader
which allows you to unread
characters. But there's the drawback: PushbackReader
does not provide a readLine
method.
Consider of using something that is already made like OpenCSV. I think that you could create something like custom mapping strategy for it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With