Merging multiple Files using Enumeration
Following is the second program on SequenceInputStream where three files are merged. The constructor takes an Enumeration object as parameter.
public class MultipleFiles
public static void main(String args) throws IOException
FileInputStream fistream1 = new FileInputStream("Sayings.txt");
FileInputStream fistream2 = new FileInputStream("Morals.txt");
FileInputStream fistream3 = new FileInputStream("abc.txt");
Vector vect = new Vector();
// obtain Enumeration object from Vector
Enumeration e = vect.elements();
// pass Enumeration object to SequenceInputStream constructor
SequenceInputStream sistream = new SequenceInputStream(e);
// destination file
FileOutputStream fostream = new FileOutputStream("bbb.txt");
while( ( temp = sistream.read() ) != -1)
System.out.print( (char) temp ); // prints at DOS prompt
fostream.write(temp); // prints in the destination file
fistream1.close(); fistream2.close(); fistream3.close();
With many source files, a different approach of coding is followed. Multiple FileInputStream objects, fistream1, fistream2 and fistream3 are created, each opening one source file. All the FileInputStream handles (objects) are added to a Vector object, vect. Using elements() method of Vector, an object Enumeration is obtained and this Enumeration object is passed to the SequenceInputStream constructor.
To write to a file, a destination file, bbb.txt, is opened with FileOutputStream object, fostream.
Now, the SequenceInputStream object sistream reads three files. It reads a byte and returns it as an ASCII integer value like as in FileToFile1.java program. The ASCII value returned is written to the destination file and converted back to char to write to the DOS prompt.