-------android培训、java培训、期待与您交流! ----------
public class MyBufferedReader extends Reader //加入到Reader体系
{
private Reader reader;
private final int BUFFER_SIZE = 1024;
private int buffSize = BUFFER_SIZE;
private char cb[] = new char[BUFFER_SIZE]; //字符缓冲
private int p = 0;//缓冲区指针
//private int cnt = 0; //缓冲区计数器
public MyBufferedReader(Reader reader)
{
this.reader = reader;
}
public int read() throws IOException //返回值是int有深义
{
int ch;
if(p == 0) //指向首元素时,对应缓冲区已空,要从硬盘读取数据填充缓冲区
{
buffSize = reader.read(cb);
if(-1 == buffSize) return -1; //读完数据
ch = cb[p++];
}
else
{
ch = cb[p]; //读取一个字符
p = (p+1) % buffSize; //循环队形
}
return ch;
}
public String readLine() throws IOException //readLine其实已作了缓冲,上边作的缓冲是读取字符
{
StringBuilder sb = new StringBuilder(); //逻辑判断
int ch;
while(-1 != (ch=read()))//循环有两个出口
{
char c = (char)ch;
if(c == '\r')
continue;
if(c == '\n') //读取\n才会把前边的字符串输出
return sb.toString();
sb.append(c);
}
if(sb.length() > 0) return sb.toString();
return null;
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException
{
return reader.read(cbuf, off, len); //没走自定义的缓存,不知合不合适?
}
@Override
public void close() throws IOException
{
reader.close();
}
public static void main(String[] args) throws IOException
{
MyBufferedReader mbr = new MyBufferedReader(new FileReader("project.txt"));
//不用再建立读取的缓冲数组
String line = "";
while(null != (line=mbr.readLine()))
{
System.out.println(line);
}
mbr.close();
}
}
-------
android培训
、
java培训
、期待与您交流! ----------