package IODemo;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
/**
* 自定义的读取缓冲区。其实就是模拟一个BufferedFileReader.
*
* 分析:
* 缓冲区中无非就是封装了一个数组,
* 并对外提供了更多的方法对数组进行访问。
* 其实这些方法最终操作的都是数组的角标。
*
* 缓冲的原理:
* 其实就是从源中获取一批数据装进缓冲区中。
* 在从缓冲区中不断的取出一个一个数据。
*
* 在此次取完后,在从源中继续取一批数据进缓冲区。
* 当源中的数据取光时,用-1作为结束标记。
*
*
* @author Administrator
*
*/
public class MyBufferedReader {
public static void main(String args[]) throws IOException {
FileReader fr = new FileReader("Demo.txt");
MyBufferedReader bufr = new MyBufferedReader(fr);
String line = null;
while ((line = bufr.myReadLine()) != null) {
System.out.println(line);
}
bufr.myClose();
}
private void myClose() throws IOException {
r.close();
}
/**
* @param args
*/
private FileReader r;
// 自定义缓冲区,需要关联一个被缓冲的对象,所以在构造函数中传入一个FileReader对象
public MyBufferedReader(FileReader r) {
this.r = r;
}
// 定义指针标记,用于操作缓冲数组中的元素,指针不断后移,当操作到最后一个元素后,指针应该归零。
private int pos = 0;
private char[] buf = new char[1024];
// 定义计数器,用于统计缓冲区中的元素个数,当该数为0时,继续从源取数据到缓冲区中
private int count = 0;
//此处犯了一个错误,else-if和多个if的区别没有搞清楚
/*
* if(a){
* b;
* }
* if(c){
* d;
* }
* a,c两个条件都会判断,但如果第二个换成else-if则第一个满足以后,就不会判断第二个
*/
public int myRead() throws IOException {
if (count == 0) {
count = r.read(buf);
pos = 0;
}
if (count < 0) {
return -1;
}
char ch = buf[pos++];
count--;
return ch;
}
public String myReadLine() throws IOException {
StringBuilder sb = new StringBuilder();
int ch = 0;
while ((ch = myRead()) != -1) {
if (ch == '\r') {
continue;
}
if (ch == '\n') {
return sb.toString();
}
sb.append((char) ch);
}
// 这一步是为了保证将缓冲区中的数据全部读出,以免源中最后以后没有'\n'换行结束符号
// 但是数据已经读入到缓冲区中,保证数据的完整性,以免遗漏数据。
if (sb.length() != 0) {
return sb.toString();
}
return null;
}
}