您的位置:首页 > Web前端

使用Reader模拟实现BufferedReader效果

2015-08-21 21:58 369 查看
我们都知道BufferedReader是一个缓冲区的读取流,内部需要读取功能的成员,也就是Reader的子类。我么可以这样实现:

1:内部定义字符数组,相当于缓冲区,提高了效率

2:操作数组的下标

3:统计字符的个数

public class Demo11 {

public static void main(String[] args) throws IOException

{<pre name="code" class="java"><span style="white-space:pre">		</span>//创建输入流
FileReader fr = new FileReader("src/temp.txt");


MyBufferedReader mbr = new MyBufferedReader(fr);
// int num = 0;
// while ((num = mbr.myRead()) != -1) {
// System.out.print((char) num);
// }

String line = null;
while ((line = mbr.myReadLine()) != null) {
System.out.println(line);
}
mbr.myClose();
}
}

class MyBufferedReader {
private Reader r; // 真正读取功能的类
private char[] arr = new char[512];// 相当于缓冲区
private int index; // 数组下标
private int count; // 统计缓冲区中字符个数

public MyBufferedReader(Reader r) {
this.r = r;
}

// 实现一次读取一个的功能
public int myRead() throws IOException {
// 缓冲区中是否有数据
if (count == 0) {
// 从文件中读取数据到缓冲区,返回值读取的

字符数
count = r.read(arr);
index = 0; // 下标为0
}
if (count < 0) // 文件末尾
return -1;
// 从缓冲区中读取一个字符
int num = arr[index];
index++;// 下标+1
// 数量-1
count--;
return num;

}

// 一次读取一行
public String myReadLine() throws IOException {
StringBuilder sb = new StringBuilder();
int num;
while ((num = myRead()) != -1) {//只要是没有读到一句话的末尾那么就继续读
if (num == '\r')//如果是遇到的空格那么就继续
continue;
else if (num == '\n')//如果是换行的话那么就停止读取 返回本行的文字
return sb.toString();
else
sb.append((char) num);
}
return null;
}

// 关闭流
public void myClose() throws IOException {
r.close();
}
}


这样我们就实现了模拟BufferedReader的效果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: