JAVA之IO流学习记录(1)——自定义一个myBufferedReader的类

自定义一个myBufferedReader的类

目标需求

自己实现一个BufferedReader的类。

需求分析

  1. bufferedReader其实就是一个缓冲区,操作时将数据存入到缓冲区中,然后再从缓冲区中一个个的读出。
  2. 缓冲区其实就是一个数组,用来存储数据。
  3. 每当缓冲区存满后,再从源中提取一部份存入缓冲区,若源中没有数据了,则返回-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;
    	}
    
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值