合并流SequenceInputStream是能对多个流进行合并成一个读取流,它在构造时需要传入Enumeration,而这个只用Vector中有,所以这个多个读取流要加入Vector集合中。
注意:它只是对读取流进行合并。
它使用步骤:
1. 创建Vector<InputStream>
2. 将要合并的InputStream加入Vector
3. 通过Vector获取Enumeration
4. 创建SequenceInputStream,将Enumeration作为参数传入。
代码:
- public class SequenceDemo {
- /**
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- // TODO Auto-generated method stub
- File file1 = new File("D:\\abc.txt");
- File file2 = new File("D:\\def.txt");
- File file3 = new File("d:\\java.txt");
-
- //将三个文件封装到vector集合中
- Vector<FileInputStream> vec = new Vector<FileInputStream>();
-
- vec.add(new FileInputStream(file1));
- vec.add(new FileInputStream(file2));
- vec.add(new FileInputStream(file3));
-
- //返回Enumeration
- Enumeration<FileInputStream> enu = vec.elements();
- SequenceInputStream seq = new SequenceInputStream(enu);
- PrintStream ps = new PrintStream("d:\\合并.txt");
-
- byte[] ch = new byte[1024];
- int len = 0;
- while((len = seq.read(ch))!= -1){
- ps.write(ch, 0, len);
- }
- seq.close();
- ps.close();
- }
- }
复制代码