Java IO 体系(一): 装饰者模式

204 阅读3分钟

前言. IO中常见的使用方式

DataOutputStream out = new DataOutputStream(
    new BufferedOutputStream(
      new FileOutputStream(
        new File(file))));

提问:嵌套的原理是什么? 答:写入文件时,使用了装饰者模式 从里往外分析: new File(file) --> 将文件路径转换为真正的系统文件 new FileOutputStream(File) --> 将文件修饰成数据流(磁盘访问) new BufferedOutputStream(FileOutputStream)--> 对数据流进行包装,在内存中开辟一个buffer,每次向磁盘写文件,读满buffer缓冲区,读完了重新发起对磁盘的读取。 new DataOutputStream(BufferedOutputStream) --> 为了体现buffer的类型,由DataOutputStream对buffer进行包装

1. 装饰者模式之Android中的应用

image

image

注意: 关键点!!! Decorator类中一定要包含Component接口,这样才能各种装饰器调用的时候有一个功能的Component对象可以赋值,实现真正的修饰。

public abstract class Person{
  public String name;
  public Person(){
  }

  public Person(String name){
    this.name = name;
  }

  public abstract void show();
}

public class SinglePerson extends Person{
    public SinglePerson(String name){
        super(name);
    }
    @Override
    public void show(){
        System.out.println("我是一个孤独的人");
    }
}

public class Decorator extends Person{
    Person person;
    public Decorator(Person person){
        this.person = person;
    }

    @Override
    public void show(){
        person.show();
    }
}

public class RShoes extends Decorator{
    public RShoes(Person person){
        super(person);
    }
    @Override
    public void show(){
        super.show();
        System.out.println("穿RShoes");
    }
}

public class TShirt extends Decorator{
    public TShirt(Person person){
        super(person);
    }
    @Override
    public void show(){
        super.show();
        System.out.println("穿TShirt");
    }
}

测试

public class TestMain{
    public static void main(String[] args){
        SinglePerson singlePerson = new SinglePerson("Andy");
        RShoes rShoes = new RShoes(singlePerson);
        TShirt tShirt = new TShirt(rShoes);
        tShirt.show();

        //TShirt tShirt2 = new TShirt(new RShores(new SinglePerson("Bob")))
    }
}

2. 装饰者模式之IO中的应用

image

  1. 流式部分——最主要的部分。如:OutputStream、InputStream、Writer、Reader等
  2. 非流式部分——如:File类、RandomAccessFile类和FileDescriptor等类
  3. 其他——文件读取部分的与安全相关的类,如:SerializablePermission类,以及与本地操作系统相关的文件系统的类,如:FileSystem类和Win32FileSystem类和WinNTFileSystem类。

2.1 流式部分

字节流

image

FilterOutputSteam相当于上面例子中的Decorator类

字符流

image

OutputStreamWrite是字节与字符连接的桥梁

字符字节的区别:字符有一个Readline(),有“行”的概念 例:zip bitmap exe 用字节流 json xml用字符流

2.2 非流式部分

File
RandomAccessFile

多线程中分段下载 构造方法: RandomAccessFile raf = new RandomAccessFile(File file, String mode); 其中参数mode的值可选“r”:可读,“w”:可写,“rw”:可读写 成员方法: seek(int index);可以将指针移动到某个位置开始读写 setLength(long length);给写入文件预留空间

//每个汉字占3个字节,写入字符串的时候会有一个记录写入字符串长度的两个字节
rsf.writeUTF("一二三四"); //所以是3*4+2 = 14个字节长度

特点和优势:

  1. 既可以读也可以写 RandomAccessFile不属于InputStream和OutputStream类系的它是一个完全独立的类,所有方法(绝大多数都只属于它自己)都是自己从头开始规定的,这里面包含读写两个操作
  2. 可以指定位置读写 RandomAccessFile能在文件里面前后移动,在文件里移动用seek(),所以他的行为与其他的IO类有些根本性的不同。总而言之,它是一个直接继承Object的独立的类。只有RandomAccessFile才有seek搜索方法,而这个方法也只适用于文件