首页 > 其他 > 详细

装饰器模式

时间:2021-06-08 13:48:19      阅读:9      评论:0      收藏:0      [点我收藏+]

利用装饰器模式自己实现读取文本(带行号)

public class ReadLineTest extends Reader{
	
	private Reader in;
	
	private int count = 1;
	
	public ReadLineTest(Reader reader) {
		this.in = reader;
	}

	@Override
	public int read(char[] cbuf, int off, int len) throws IOException {
		return 0;
	}

	@Override
	public void close() throws IOException {
		in.close();
	}
	
	public String readWithLine() throws Exception{
		StringBuilder sb = new StringBuilder();
		int i;
		while(true){
			i = in.read();
			if(i == ‘\r‘){
				continue;
			}
			if(i == ‘\n‘ || i == -1){
				break;
			}
			sb.append((char)i);
		}
		if(sb.toString().length() == 0){
			if(i == ‘\n‘){
				return "";
			}else{
				return null;
			}
		}
		return (count ++) + "_" + sb.toString();
	}
	
	public static void main(String[] args) throws Exception {
		
		//这是重写的方法
		Reader reader = new FileReader("D:/1.txt");
		ReadLineTest br = new ReadLineTest(reader);
		String line;
		while((line = br.readWithLine()) != null){
			System.out.println(line);
		}
		br.close();
		
		
		
		//这是原生的方法
//		Reader reader = new FileReader("D:/1.txt");
//		BufferedReader br = new BufferedReader(reader);
//		String line;
//		while((line = br.readLine()) != null){
//			System.out.println(line);
//		}
//		br.close();
	}
}

技术分享图片
控制台输出
技术分享图片

装饰器模式

原文:https://www.cnblogs.com/kaka-qiqi/p/14861982.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!