SequenceInputStream 类表示其他输入流的逻辑串联,即文件的合并。
它从输入流的有序集合开始,并从第一个输入流开始读取,直到到达文件末尾,接着从第二个输入流读取,依次类推,直到到达包含的最后一个输入流的文件末尾为止。
SequenceInputStream 类提供了两个构造函数。我们先来看第一个。
所用的构造函数:
SequenceInputStream(InputStream s1, InputStream s2)
通过记住这两个参数来初始化新创建的 SequenceInputStream(将按顺序读取这两个参数,先读取 s1,然后读取 s2),
以提供从此 SequenceInputStream 读取的字节。 即将文件 file1 和文件 file2 合并至文件 file3 中。
代码如下:
public static void SequenceTest1(String file1, String file2,String file3){ try { FileInputStream iStream1 = new FileInputStream(new File(file1)); FileInputStream iStream2 = new FileInputStream(new File(file2)); FileOutputStream iStream3 = new FileOutputStream(new File(file3)); InputStream si = new SequenceInputStream(iStream1, iStream2); byte[] arr = new byte[1024*20]; int len = 0; while ((len = si.read(arr))!=-1) { iStream3.write(arr,0,len); iStream3.flush();//刷新此缓冲的输出流。 } si.close(); iStream3.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
方法二是通过记住参数来初始化新创建的 SequenceInputStream,该参数必须是生成运行时类型为 InputStream 对象的 Enumeration 型参数。
即通过集合类的方式来传递文件的地址参数。
Java代码:
public static void SequenceTest3(String file1, String file2,String file3,String file4){ SequenceInputStream iStream = null; BufferedOutputStream bStream = null; Vector<InputStream >vector = new Vector<InputStream>(); try { vector.addElement(new FileInputStream(new File(file1))); vector.addElement(new FileInputStream(new File(file2))); vector.addElement(new FileInputStream(new File(file3))); Enumeration<InputStream>enumeration = vector.elements(); iStream = new SequenceInputStream(enumeration); bStream = new BufferedOutputStream(new FileOutputStream(new File(file4))); byte[] arr = new byte[1024*20]; int len = 0; while ((len = iStream.read(arr))!=-1) { bStream.write(arr, 0, len); bStream.flush();//刷新此缓冲的输出流。 } iStream.close(); bStream.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public static void SequenceTest4(String[] filesrc,String fileresult){ SequenceInputStream iStream = null; BufferedOutputStream bStream = null; Vector<InputStream >vector = new Vector<InputStream>(); try { for (int i = 0; i < filesrc.length; i++) { vector.addElement(new FileInputStream(new File(filesrc[i]))); } Enumeration<InputStream>enumeration = vector.elements(); iStream = new SequenceInputStream(enumeration); bStream = new BufferedOutputStream(new FileOutputStream(new File(fileresult))); byte[] arr = new byte[1024*20]; int len = 0; while ((len = iStream.read(arr))!=-1) { bStream.write(arr, 0, len); bStream.flush();//刷新此缓冲的输出流。 } iStream.close(); bStream.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
String[] arr = {"1.txt", "2.txt","33.txt","333.txt"}; SequenceTest4(arr, "w.txt");