public class MyBufferedReader {
private FileReader f;
// 定义一个数组作为缓冲区
private char[] buf = new char[1024];
// 定义一个指针用来操作数组中的元素,当操作到最后一个元素后指针归零
private int pos = 0;
// 定义一个计数器用来计算缓冲区中的数据个数,当为0时,继续取数据到缓冲区中
private int count = 0;
MyBufferedReader(FileReader f) {
this.f = f;
}
/**
* 缓冲区中读
* @return
* @throws IOException
*/
public int myRead() throws IOException {
// 源中取数据到缓冲区中,计数器为0才取
if(count==0){
count = f.read(buf);
pos = 0;
}
if(count==-1){
return -1;
}
char ch = buf[pos];
pos++;
count--;
return ch;
/*if (count == 0) {
count = f.read(buf);
if (count == -1)
return -1;
//获取数据到缓冲区后指针归0
pos = 0;
char ch = buf[pos];
pos++;
count--;
return ch;
} else if (count > 0) {
char ch = buf[pos];
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;
}
public void close() throws IOException {
f.close();
}
}