黑马程序员--javaIO 之BufferedReader

-------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培训 、期待与您交流!     ----------  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值