自定义一个myBufferedReader的类
目标需求
自己实现一个BufferedReader的类。
需求分析
- bufferedReader其实就是一个缓冲区,操作时将数据存入到缓冲区中,然后再从缓冲区中一个个的读出。
- 缓冲区其实就是一个数组,用来存储数据。
- 每当缓冲区存满后,再从源中提取一部份存入缓冲区,若源中没有数据了,则返回-1,用以结束。
代码实现
准备部分代码:
private Read r;
private char[] buff = new char[1024]; //定义一个缓冲区
private int count = 0; //定义一个计数器。判断是否取完
private int pos = 0; //定义一个指针
read方法实现:
public int myRead(){
if(count==0){
count = r.read(buff);
pos = 0; //每次重新取数据时指针应该置0
}
if(count<0)
return -1;
char ch = buff(pos++);
count--;
return ch;
}
readLine方法实现:
public String myReadLine(){
StringBuilder sb = new StringBuilder();
int ch = 0;
while((ch=myRead())!=null){
if(ch='\r')
continue;
if(ch='\n')
return sb.toString();
sb.append((char)ch);
}
//健壮性判断
if(sb.length!=0)
return sb.toString();
return null;
}
完整代码
public class MyBufferedReader extends Reader {
private Reader r;
private char[] buf = new char[1024];
private int pos;
private int count = 0;
public MyBufferedReader(Reader r) {
this.r = r;
}
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);
}
if (sb.length() != 0)
return sb.toString();
return null;
}
@Override
public void close() throws IOException {
}
@Override
public int read(char[] arg0, int arg1, int arg2) throws IOException {
return 0;
}
}