«Back to Home

Core Java

Topics

SequenceInputStream Class In Java

SequenceInputStream Class
 
To read data from the multiple streams, SequenceInputStream class is used and the data is read by it one by one.
 
Constructors of SequenceInputStream class

SequenceInputStream(InputStream s1, InputStream s2)

It is used to create a new input stream by reading the data of two input stream in order, first s1 and then s2.
 
SequenceInputStream(Enumeration e)

It is used to create a new input stream by reading the data of an enumeration whose type is InputStream.
 
Let’s see an example, given below.
 
Code
  1. import java.io.*;  
  2. public class FileHandlingExample {  
  3.     public static void main(String args[]) throws Exception {  
  4.         FileInputStream fis1 = new FileInputStream("file1.txt");  
  5.         FileInputStream fis2 = new FileInputStream("file2.txt");  
  6.         SequenceInputStream s = new SequenceInputStream(fis1, fis2);  
  7.         int i;  
  8.         while ((i = s.read()) != -1) {  
  9.             System.out.println((char) i);  
  10.         }  
  11.         s.close();  
  12.         fis1.close();  
  13.         fis2.close();  
  14.     }  
  15. }  
11
 
In the example, mentioned above, first read the files one by one and then print the data of both the files file1.txt and file2.txt.
 
Let’s see another example, given below.
 
Code
  1. import java.io.*;  
  2. public class FileHandlingExample {  
  3.     public static void main(String args[]) throws Exception {  
  4.         FileInputStream fis1 = new FileInputStream("file1.txt");  
  5.         FileInputStream fis2 = new FileInputStream("file2.txt");  
  6.         FileOutputStream fos = new FileOutputStream("file3.txt");  
  7.         SequenceInputStream s = new SequenceInputStream(fis1, fis2);  
  8.         int i;  
  9.         while ((i = s.read()) != -1) {  
  10.             fos.write(i);  
  11.         }  
  12.         s.close();  
  13.         fos.close();  
  14.         fis1.close();  
  15.         fis2.close();  
  16.     }  
  17. }  
12

In the example, mentioned above, we are writing the data of the two files file1.txt and file2.txt into another file named file3.txt.
 
Summary

Thus, we learnt to read the data from the multiple streams, SequenceInputStream class is used in Java and also learnt how we can create it.