读书人

装饰模式在Java I/O库中的使用

发布时间: 2013-01-21 10:15:39 作者: rapoo

装饰模式在Java I/O库中的应用

装饰模式在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();

}

}

}

读书人网 >软件架构设计

热点推荐