装饰者模式(Decorator Pattern) Java的IO类 使用方法
Java的IO类使用装饰者模式进行扩展, 其中FilterInputStream类, 就是装饰者(decorator)的基类.
实现其他装饰者(decorator), 需要继承FilterInputStream类.
代码:
/**
* @time 2014年5月23日
*/
package decorator.io;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @author C.L.Wang
*
*/
public class LowerCaseInputStream extends FilterInputStream {
public LowerCaseInputStream(InputStream in) {
super(in);
}
public int read() throws IOException {
int c = super.read();
return (c==-1 c : Character.toLowerCase((char)c));
}
public int read(byte[] b, int offset, int len) throws IOException {
int result = super.read(b, offset, len);
for (int i=offset; i
测试:
/**
* @time 2014年5月23日
*/
package decorator.io;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @author C.L.Wang
*
*/
public class InputTest {
/**
* @param args
*/
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
int c;
try{
InputStream in = new LowerCaseInputStream(new BufferedInputStream(new FileInputStream(test.txt)));
while ((c = in.read()) >= 0) {
System.out.print((char)c);
}
in.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
通过装饰
具体组件类FileInputStream, 实现格式的更改.
注意:Java的文件的默认读取路径为项目的根目录.
