How to merge multiple files using SequenceInputStream - Mar Java Mit Java

How to merge multiple files using SequenceInputStream

Imagine you have multiple source files whose data you need to merge into a single file. Using simple FileInputStream API this can be done. You will read each file sequentially and write it to FileOutputStream. But java API provides a simpler API to achieve the same, SequenceInputStream

In this example we create two FileInputStreams to read data from two files and pass them as constructor to SequenceInputStream. Files can also be passed as vector. SequenceInputStream will take care of reading data sequentially from the input files and outputting them

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class FileSequennceInputStream {
	public static void main(String[] args) throws Exception {
 
		FileInputStream fis1 = new FileInputStream(new File(
				"c:\\downloads\\a.txt"));
		FileInputStream fis2 = new FileInputStream(new File(
				"c:\\downloads\\b.txt"));
 
		SequenceInputStream sis = new SequenceInputStream(fis1, fis2);
		FileOutputStream fos = new FileOutputStream(new File("c:\\downloads\\c.txt"));
		int b = 0;
		while ((b = sis.read()) != -1) {
			fos.write(b);
		}
	}
}

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *