装饰者模式

来源:互联网 发布:php 去掉斜线 编辑:程序博客网 时间:2024/05/22 07:40

package test.java.io;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 装饰者模式
 * 用LowerInputStream包装流,将经过该流的字母全部转换成小写的
 */
public class LowerInputStream extends FilterInputStream {

 public LowerInputStream(InputStream in) {
  super(in);
 }

 @Override
 public int read() throws IOException {
  int c = super.read();
  return c == -1 ? c: Character.toLowerCase(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+len; i++) {
   b[i] = (byte) Character.toLowerCase(b[i]);
  }
  
  return result;
 }
 
 
 public static void main(String[] args) {
  InputStream in = null;
  int c = 0;
  try {
   in = new LowerInputStream(new BufferedInputStream(new FileInputStream("test.txt")));
   
   while((c = in.read()) >= 0) {
    System.out.print((char)c);
   }
   
   in.close();
  } catch (Exception e) {
  }
 }
}

原创粉丝点击