java IO流之装饰者

我们知道在java整个IO流的API设计中大量采用了装饰者模式进行设计。而装饰者模式最主要的特征是可以创建自己装饰者的装饰者,因此我们可以利用IO流中采用了装饰者这个特征根据需求去扩展自己的IO流。

例如现在有这样一个需求:读取一个文件里面的内容,将文件里的内容所有的小写字母都转换成大写的。这个时候我们就可以通过去扩展IO流去做。


package com.unis.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilterReader;
import java.io.IOException;
import java.io.Reader;

public class UppCaseReader extends FilterReader {

public UppCaseReader(Reader in) {
super(in);
}

@Override
public int read(char[] cbuf, int off, int len) throws IOException {
int result = super.read(cbuf, off, len);
for(int i=off;i<len;i++){
if(cbuf[i]>='a'&&cbuf[i]<='z'){
cbuf[i] -= 32;
}
}
return result;
}

// @Override
// public int read() throws IOException {
// int result = super.read();
// if(result>='a'&&result<='z'){
// result-=32;
// }
// return result;
// }

public static void main(String[] args) throws IOException {
Reader reader = new BufferedReader(new UppCaseReader(new FileReader(new File("src/com/unis/io/UppCaseReader.java"))));
int i =0;
while((i=reader.read())!=-1){
System.out.print((char)i);
}
}
}



注:1.在这个类中我们也可以直接继承Reader这个类,但是如果继承Reader类除了要复写read方法(带三个参数的),我们还要复写colse方法。

2.另外在这个类中为什么我们要复写read方法(带三个参数的),而不复写不带参数的read方法呢。这是因为Reader类中所有的read方法到最后都是去调用带三个参数的read方法去实现的,所以我们只用去实现三个参数的read方法即可。

3.在构造方法中传入的reader才是真的reader.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值