以装饰者模式看IO
以前经常对IO的概念及其中大量的类理解不清,这里先简单整理一下
一 IO
-
首先流的概念
使用inputStream对file进行读取,使用outputStream对文件进行写入 - 流的分类
- 字节流(8 位)
- 字节输入流:InputStream,是所有字节输入流的祖先
- 字节输出流:OutputStream,是所有字节输出流的祖先
- 字符流(16 位Unicode)
- 字符输入流:Reader ,是所有字符输入流的祖先
- 字符输出流:Writer,是所有字符输出流的祖先
- IO字节流整体分类
单看,InputStream一块,FileInputStream和BuffededInputStream等同样继承于InputStream这个超类。 FileInputStream(或其他InputStream的子类,FilterInputStream除外)可以被看做被包装者,BufferedInputStream(或其他FilterInputStream)是包装者,为FileInputStream提供额外的封装方法。
二 小例
在这个例子中,要求自定义包装者,将输入流内的所有大写字符换成小写。
-
创建新类继承自FilterInputStream,重写read方法
public class LowerCaseInputStream extends FilterInputStream { @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 off, int len) throws IOException { int c = super.read(b, off, len); for(int i= off;i<off+len;i++){ b[i] = (byte) Character.toLowerCase((b[i])); } // TODO Auto-generated method stub return c; } protected LowerCaseInputStream(InputStream in) { super(in); } }
- 创建测试类, 这里在测试方法中用了个向文件写入和读出的部分代码:
其中,Writer writer = new OutputStreamWriter(new FileOutputStream(f)); 对字节输出流进行封装,成为字符输出流,方便了对字符串的直接操作。public static void main(String[] args) { File f = new File("d:\\test\\testIO.txt"); try { f.createNewFile();//create new file //write string into the file String str = "Hello,I Want To Change The World!"; Writer writer = new OutputStreamWriter(new FileOutputStream(f)); writer.write(str); writer.close(); System.out.println("Write the bytes into the file:"+ str); //get file info to bytes,change the upper cast to lower case InputStream is = new LowerCaseInputStream(new FileInputStream(f)); byte[] readBytes = new byte[33]; is.read(readBytes); String readString = new String(readBytes); System.out.println("Read the file,and lower the case :"+ readString); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
三 其他的
类似于InputStream,OutputStream也同样使用了装饰者模式。
另附上字符流的类图