Java SequenceInputStream class is used to read data from multiple streams. It reads data of streams one by one.
Constructors of SequenceInputStream class:
Constructor | Description |
1) SequenceInputStream(InputStream s1, InputStream s2) | creates a new input stream by reading the data of two input stream in order, first s1 and then s2. |
2) SequenceInputStream(Enumeration e) | creates a new input stream by reading the data of an enumeration whose type is InputStream. |
Simple example of SequenceInputStream class
In this example, we are printing the data of two files f1.txt and f2.txt.
- import java.io.*;
- class Simple{
- public static void main(String args[])throws Exception{
- FileinputStream fin1=new FileinputStream("f1.txt");
- FileinputStream fin2=new FileinputStream("f2.txt");
-
- SequenceinputStream sis=new SequenceinputStream(fin1,fin2);
- int i;
- while((i=sis.read())!=-1){
- System.out.println((char)i);
- }
- sis.close();
- fin1.close();
- fin2.close();
- }
- }
Example of SequenceInputStream that reads the data from two files
In this example, we are writing the data of two files f1.txt and f2.txt into another file named f3.txt.
-
-
- import java.io.*;
- class Simple{
- public static void main(String args[])throws Exception{
-
- FileinputStream fin1=new FileinputStream("f1.txt");
- FileinputStream fin2=new FileinputStream("f2.txt");
-
- FileOutputStream fout=new FileOutputStream("f3.txt");
-
- SequenceinputStream sis=new SequenceinputStream(fin1,fin2);
- int i;
- while((i.sisread())!=-1)
- {
- fout.write(i);
- }
- sis.close();
- fout.close();
- fin.close();
- fin.close();
-
- }
- }
Example of SequenceInputStream class that reads the data from multiple files using enumeration
If we need to read the data from more than two files, we need to have these information in the Enumeration object. Enumeration object can be get by calling elements method of the Vector class. Let's see the simple example where we are reading the data from the 4 files. |
- import java.io.*;
- import java.util.*;
-
- class B{
- public static void main(String args[])throws IOException{
-
-
- FileInputStream fin=new FileInputStream("A.java");
- FileInputStream fin2=new FileInputStream("abc2.txt");
- FileInputStream fin3=new FileInputStream("abc.txt");
- FileInputStream fin4=new FileInputStream("B.java");
-
-
- Vector v=new Vector();
- v.add(fin);
- 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();
- fin.close();
- fin2.close();
- }
- }
No comments:
Post a Comment