• 设计模式


    装饰者模式(Decorator Pattern) Java的IO类 用法


    本文地址: http://blog.csdn.net/caroline_wendy/article/details/26716823


    装饰者模式(decorator pattern)參见: http://blog.csdn.net/caroline_wendy/article/details/26707033


    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<offset+result; ++i) {
    			b[i] = (byte)Character.toLowerCase((char)b[i]);
    		}
    		return result;
    	}
    }
    

    測试:

    /**
     * @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的文件的默认读取路径为项目的根文件夹.






  • 相关阅读:
    全文索引的书
    图片上传预览
    sqlserver 递归删除组织结构树
    dataset 转泛型list
    jquery easyui tree 异步加载数据
    sqlserver 禁用外键
    linx 实用操作命令二
    Compilation failed: this version of PCRE is not compiled with PCRE_UTF8 support at offset 0
    Centos linux php扩展安装步骤
    linux Apache和php配置
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4021668.html
Copyright © 2020-2023  润新知