装饰者java.io类,编写一个装饰者,把输入流内的所有字符倒序输出。
利用IO输出流实现装饰者模式的应用,把文件读取出来,然后倒序输出
装饰java.io类图
具体实现,新建LCInputStream一个类,实现抽象组件InputStream。LCInputStream类就是具体被装饰者
代码如下:
package la1;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public class LCInputStream extends FilterInputStream {
protected LCInputStream(InputStream in) {
super(in);
}
public int read() throws IOException{
int c=super.read();
return c;
}
//倒序输出内容
public int read(byte[]b,int off,int len) throws IOException{
int s=super.read(b, off, len);
byte[] a=new byte[b.length];
for(int i=off;i<b.length;i++){
a[i]=b[b.length-i-1];
System.out.print((char)a[i]);
}
return s;
}
}
编写测试类:
package la1;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class Test {
public static void main(String[] args) throws IOException {
int c;
InputStream in=new LCInputStream(
new BufferedInputStream(
new FileInputStream("F:\\test.txt")));
int a=in.available()+1;
byte[] b= new byte[a];
in.read(b,0,a);
in.close();
}
}
运行测试类,然后就大功告成了。