articles

SequenceInputStream Class in Java

Anupam Mishra 4806 02-Dec-2015

In Java, SequenceInputStream class is used for reading data from multiple stream or files.

For example, we have created two different files and taken two strings for writing one after another of these files with the help of FileOutputStream class. Then we created a one object of SequenceInputStream class for reading existing file and we have write to another file of those contents

import java.io.*;  class SequenceInput{ 
public static void. main(String args[])throws Exception{ 
FileOutputStream fout1=new FileOutputStream("SequenceInputStream1.txt"); 
FileOutputStream fout2=new   FileOutputStream("SequenceInputStream2.txt"); 
FileInputStream fin1=new FileInputStream("SequenceInputStream1.txt"); 
FileInputStream fin2=new FileInputStream("SequenceInputStream2.txt"); 
String s="Sachin Tendulkar";
String s1="Viru"; 
byte b[]=s.getBytes();//converting string into byte array 
fout1.write(b);
byte c[]=s1.getBytes();//converting string into byte array 
fout2.write(c);
FileOutputStream fout=new   FileOutputStream("SequenceInputStreamFinal.txt"); 
SequenceInputStream ss=new SequenceInputStream(fin1,fin2); 
int i; 
while((i=ss.read())!=-1) 

fout.write(i);     

System.out.println(“Successfully Done!...”)
ss.close(); 
fout.close();   
fin1.close();   
fin2.close();   }  } 
Output:
Successfully Done!... 

If we need to read the data from more than two files

 We need to have theseinformation in the Enumeration object. Enumeration object can be get by callingelements method of the Vector class. Now, we are reading the data from the 4 existing files.    

    import java.io.*; import java.util.*; 
    class UsingEnum{ 
    public static void main(String args[])throws IOException
    { 
    FileInputStream fin1=new FileInputStream("SequenceInputStream1.txt"); 
    FileInputStream fin2=new FileInputStream("SequenceInputStream1.txt"); 
    FileInputStream fin3=new FileInputStream("Fil.txt"); 
    FileInputStream fin4=new FileInputStream("Flood.java");  
    Vector v=new Vector(); 
    v.add(fin1); 
    v.add(fin2); 
    v.add(fin3); 
    v.add(fin4);  
    Enumeration e=v.elements();  SequenceInputStream bin=new SequenceInputStream(e); 
    int i=0;   while((i=bin.read())!=-1){     System.out.print((char)i); 
    } 
    bin.close(); 
    fin1.close(); 
    fin2.close(); 
    } 
    } 

Output:

Sachin Tendulkar
Sachin Tendulkar
India is a good country I
ndia is a good country


Updated 12-Sep-2018

Leave Comment

Comments

Liked By