Java SequenceInputStream class

Introduction

The SequenceInputStream class can concatenate multiple InputStream.

A SequenceInputStream constructor uses either a pair of InputStream or an Enumeration of InputStream as its argument:

SequenceInputStream(InputStream first , InputStream second)  
SequenceInputStream(Enumeration <? extends InputStream> streamEnum) 

The following code uses a SequenceInputStream to output the contents of two files.

// Demonstrate sequenced input. 

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Vector;

class InputStreamEnumerator implements Enumeration<FileInputStream> {
   private Enumeration<String> files;

   public InputStreamEnumerator(Vector<String> files) {
      this.files = files.elements();
   }/*ww  w . j av a 2 s  . co m*/

   public boolean hasMoreElements() {
      return files.hasMoreElements();
   }

   public FileInputStream nextElement() {
      try {
         return new FileInputStream(files.nextElement().toString());
      } catch (IOException e) {
         return null;
      }
   }
}

public class Main {
   public static void main(String args[]) throws Exception {
      int c;
      Vector<String> files = new Vector<String>();

      files.addElement("file1.txt");
      files.addElement("file2.txt");
      files.addElement("file3.txt");
      InputStreamEnumerator ise = new InputStreamEnumerator(files);
      InputStream input = new SequenceInputStream(ise);

      while ((c = input.read()) != -1)
         System.out.print((char) c);
      input.close();
      System.out.println("Error Closing SequenceInputStream");

   }
}



PreviousNext

Related