问题描述
我正在解析.cvs文件.对于cvs的每一行,我都会创建一个具有解析值的对象,并将它们放入集合中.
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.
在将对象放入地图并循环到下一个对象之前,我需要检查下一个cvs的行是否与实际对象相同,但特定属性值不同.
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.
例如:
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.
}
推荐答案
-
您可以使用
BufferedReader.mark(int)
.要返回到该位置,请调用BufferedReader.reset()
.mark
的参数是预读限制";如果您尝试读取的内容超过了限制,而又尝试reset()
,则可能会得到IOException.
You can mark the current position using
BufferedReader.mark(int)
. To return to the position you callBufferedReader.reset()
. The parameter tomark
is the "read ahead limit"; if you try toreset()
after reading more than the limit you may get an IOException.
或者您可以使用 RandomAccessFile
代替:
Or you could use RandomAccessFile
instead:
// Get current position
long pos = raf.getFilePointer();
// read more lines...
// Return to old position
raf.seek(pos);
或者您可以使用 PushbackReader
,您可以输入unread
个字符.但是有一个缺点:PushbackReader
不提供readLine
方法.
Or you could use PushbackReader
which allows you to unread
characters. But there's the drawback: PushbackReader
does not provide a readLine
method.
这篇关于Java BufferedReader在循环之前检查循环的下几行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!