用Java中的BufferedReader重置缓冲区? [英] Reset buffer with BufferedReader in Java?

查看:1766
本文介绍了用Java中的BufferedReader重置缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用BufferedReader类在缓冲区中逐行读取。当读取缓冲区的最后一行时,我想再次从缓冲区的开始读取。
我已经阅读了mark()和reset(),我不确定它的用法,但我不认为他们可以帮我解决这个问题。



有没有人知道如何开始从缓冲区开始读取后到达最后一行?像我们可以使用RandomAccessFile的seek(0)?请。
谢谢

解决方案

标记/重置是你想要的,但是你不能真的在BufferedReader上使用它,因为它只能重置一定数量的字节(缓冲区大小)。如果你的文件比这个大,它将不起作用。 (不幸的是)没有简单的方法,但是处理起来并不难,你只需要一个原始的FileInputStream的句柄。

  FileInputStream fIn = ...; 
BufferedReader bRead = new BufferedReader(new InputStreamReader(fIn));

// ...通读b阅读...

//reset到文件开头(丢弃旧的缓冲读取器)
fIn.getChannel ).POSITION(0);
bRead = new BufferedReader(new InputStreamReader(fIn));

(注意,不建议使用默认的字符集,只是使用一个简单的例子)。 >

I am using class BufferedReader to read line by line in the buffer. When reading the last line in the buffer, I want to start reading from the beginning of the buffer again. I have read about the mark() and reset(), I am not sure its usage but I dont think they can help me out of this.

Does anyone know how to start reading from the beginning of the buffer after reaching the last line? Like we can use seek(0) of the RandomAccessFile? Please. Thanks

解决方案

mark/reset is what you want, however you can't really use it on the BufferedReader, because it can only reset back a certain number of bytes (the buffer size). if your file is bigger than that, it won't work. there's no "simple" way to do this (unfortunately), but it's not too hard to handle, you just need a handle to the original FileInputStream.

FileInputStream fIn = ...;
BufferedReader bRead = new BufferedReader(new InputStreamReader(fIn));

// ... read through bRead ...

// "reset" to beginning of file (discard old buffered reader)
fIn.getChannel().position(0);
bRead = new BufferedReader(new InputStreamReader(fIn));

(note, using default character sets is not recommended, just using a simplified example).

这篇关于用Java中的BufferedReader重置缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆