装饰模式在Java I/O库中的应用
编写一个装饰者把所有的输入流内的大写字符转化成小写字符:
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public class LowerCaseInputStream extends FilterInputStream
{
protected LowerCaseInputStream(InputStream in)
{
super(in);
}
@Override
public int read() throws IOException
{
int c = super.read();
return (c == -1 ? c : Character.toLowerCase((char) c));
}
@Override
public int read(byte[] b, int offset, int len) throws IOException
{
int result = super.read(b, offset, len);
for (int i = offset; i < offset + result; i++)
{
b[i] = (byte) Character.toLowerCase((char) b[i]);
}
return result;
}
}
测试我们的装饰者类:
import java.io.*;
public class InputTest
{
public static void main(String[] args) throws IOException
{
int c;
try
{
InputStream in = new LowerCaseInputStream(new BufferedInputStream(
new FileInputStream("D:\\test.txt")));
while ((c = in.read()) >= 0)
{
System.out.print((char) c);
}
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}