Java序列流SequenceInputStream

SequenceInputStream :对多个流进行合并。

构造方法

SequenceInputStream(Enumeration<? extends InputStream> e)
通过记住参数来初始化新创建的 SequenceInputStream,该参数必须是生成运行时类型为 InputStream 对象的 Enumeration 型参数。

SequenceInputStream(InputStream s1, InputStream s2)
通过记住这两个参数来初始化新创建的 SequenceInputStream(将按顺序读取这两个参数,先读取 s1,然后读取 s2),以提供从此 SequenceInputStream 读取的字节。

 

SequenceInputStreamDemo.java

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Vector;

public class SequenceInputStreamDemo {

   public static void main(String[] args) throws IOException {
      method_1();
      method_2();
   }
   // 两个读取流
   public static void method_1() throws FileNotFoundException, IOException {
      FileInputStream fis1 = new FileInputStream("C:\\1.txt");
      FileInputStream fis2 = new FileInputStream("C:\\2.txt");
      SequenceInputStream sis = new SequenceInputStream(fis1, fis2);
      FileOutputStream fos = new FileOutputStream("C:\\1_2.txt");
      byte buf[] = new byte[1024];
      int ch = 0;
      while ((ch = sis.read(buf)) != -1) {
         fos.write(buf, 0, ch);
         fos.flush();
      }
      fos.close();
      sis.close();
   }

   // 多个读取流
   public static void method_2() throws IOException {
      Vector<FileInputStream> v = new Vector<FileInputStream>();
      v.add(new FileInputStream("C:\\1.txt"));
      v.add(new FileInputStream("C:\\2.txt"));
      v.add(new FileInputStream("C:\\3.txt"));
      Enumeration<FileInputStream> en = v.elements();
      SequenceInputStream sis = new SequenceInputStream(en);
      FileOutputStream fos = new FileOutputStream("C:\\1-2-3.txt");
      int len = 0;
      byte buf[] = new byte[1024];
      while ((len = sis.read(buf)) != -1) {
         fos.write(buf, 0, len);
         fos.flush();
      }
      fos.close();
      sis.close();
   }
}