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

本文介绍如何利用Java的装饰者模式扩展IO类,以实现对文件输入流的格式转换。通过继承FilterInputStream类,演示了如何创建自定义装饰者类来更改数据格式,例如将文件输入流中的字符转换为小写。并通过测试代码验证了此模式在实际应用中的可行性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


本文地址: http://blog.youkuaiyun.com/caroline_wendy/article/details/26716823


装饰者模式(decorator pattern)參见: http://blog.youkuaiyun.com/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的文件的默认读取路径为项目的根文件夹.






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值