5.29把分散的文件合并

5.29把分散的文件合并

本质就是拷贝,只是在拷贝的时候不是重写而是追加

    /**
    * 几个步骤
    * 选择输出流--->文件输出位置
    * 选择输入流--->被打散的文件的位置(这里注意要循环操作,因为文件已经被拆分成很多份)
    * 拷贝--->文件读取操作
    * @param destPath
    * @throws IOException
    */
   public void merge(String destPath) throws IOException{
       //选择输出流
       OutputStream os = new BufferedOutputStream(new FileOutputStream(destPath, true));
       //选择输入流
       for (int i = 0; i < destPaths.size(); i++){
           InputStream is = new BufferedInputStream(new FileInputStream(destPaths.get(i)));
           /*进行文件拷贝*/
           /*
           1、分段读取进入缓冲容器
           2、设置接收长度
           3、分段写出
            */
           /*设置缓冲容器*/
           byte[] flush = new byte[1024];
           /*设置接收长度*/
           int len = -1;
           /*分段写出*/
           while ((len=is.read(flush))!=-1){
               os.write(flush, 0, len);
          }
           /*刷新流*/
           os.flush();
           /*关闭流--->先打开的后关闭,循环的流后面关闭*/
           is.close();
      }
       os.close();
  }
SequenceInputStream是其他输入流的逻辑基点

其构造器要么放入两个节点要么放入多个节点

  • 放入多个节点要实现Enumeration接口

  • SequenceInputStream(Enumeration<? extends InputStream> e) 初始化新创建 SequenceInputStream通过记住参数,它必须是一个 Enumeration产生对象,它们的运行时类型是 InputStream

Enumeration接口
  • 实现枚举接口的对象生成一系列元素,一次一个。 连续调用nextElement方法返回系列的连续元素。

  • Vector<E> v 
    for (Enumeration<E> e = v.elements(); e.hasMoreElements();)
          System.out.println(e.nextElement());

同步容器

    /**
    * 几个步骤
    * 选择输出流--->文件输出位置
    * 选择输入流--->被打散的文件的位置(这里注意要循环操作,因为文件已经被拆分成很多份)
    * 拷贝--->文件读取操作
    * @param destPath
    * @throws IOException
    */
   public void merge(String destPath) throws IOException{
       //选择输出流
       OutputStream os = new BufferedOutputStream(new FileOutputStream(destPath, true));
       Vector<InputStream> vi = new Vector<InputStream>();
       SequenceInputStream sis = null;
       //选择输入流
       for (int i = 0; i < destPaths.size(); i++){
           InputStream is = new BufferedInputStream(new FileInputStream(destPaths.get(i)));
      }
       sis = new SequenceInputStream(vi.elements());
       /*进行文件拷贝*/
           /*
           1、分段读取进入缓冲容器
           2、设置接收长度
           3、分段写出
            */
       /*设置缓冲容器*/
       byte[] flush = new byte[1024];
       /*设置接收长度*/
       int len = -1;
       /*分段写出*/
       while ((len=sis.read(flush))!=-1){
           os.write(flush, 0, len);
      }
       /*刷新流*/
       os.flush();
       /*关闭流--->先打开的后关闭,循环的流后面关闭*/
       sis.close();
       os.close();
       /*
       1、将输入流放入容器中--->输入流是BuffereInputStream容器是Vector
       2、再将容器放入序列流当中
       3、进行文件拷贝的操作
        */
  }
It's a lonely road!!!
原文地址:https://www.cnblogs.com/JunkingBoy/p/14825203.html