Java BufferedReader在循环之前检查循环的下一行

And*_*zzi 7 java loops bufferedreader

我正在解析.cvs文件.对于cvs的每一行,我使用解析的值创建一个对象,并将它们放入一个集合中.

在将对象放入地图并循环到下一个之前,我需要检查下一个cvs的行是否与实际对象相同,但具有不同的特定属性值.

为此,我需要检查缓冲区的下一行,但是将循环的缓冲区保持在相同的位置.

例如:

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.
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*oni 8

  1. 您可以使用标记当前位置BufferedReader.mark(int).要回到你打电话的位置BufferedReader.reset().参数to mark是"预读限制"; 如果您reset()在读取超过限制后尝试读取IOException.

  2. 或者你可以使用RandomAccessFile:

    // Get current position
    long pos = raf.getFilePointer();
    // read more lines...
    // Return to old position
    raf.seek(pos);
    
    Run Code Online (Sandbox Code Playgroud)
  3. 或者您可以使用PushbackReader它允许您使用unread角色.但是有缺点:PushbackReader没有提供readLine方法.

  • 我如何使用input.mark()方法?我的意思是.我需要传递一个参数(我猜它是我要标记的位置),但是我如何检索它,因为我正在阅读线条? (3认同)