SequenceInputStream表示其他输入流的逻辑串联。
它从输入流的有序集合开始,从第一个开始读取,直到到达文件末尾,然后从第二个开始读取,依此类推,直到在最后一个包含的输入流中到达文件末尾
构造函数
SequenceInputStream(InputStream s1, InputStream s2)
SequenceInputStream(Enumeration<? extends InputStream> e)
实例:
1 //将1.txt,2.txt,3.txt文件合并到一个文件中 2 /* 3 * 方式一、Vector集合是可行的,但效率低 4 */ 5 /* Vector<FileInputStream> vector=new Vector<FileInputStream>(); 6 vector.add(new FileInputStream("1.txt")); 7 vector.add(new FileInputStream("2.txt")); 8 vector.add(new FileInputStream("3.txt")); 9 Enumeration<FileInputStream> en=vector.elements(); 10 SequenceInputStream ss=new SequenceInputStream(en); */ 11 12 /* 13 * 方式二、使用ArrayList集合效率高 14 * 使用集合工具类Collections.enumeration方法将ArrayList集合转成Enumeration<FileInputStream>型对象 15 */ 16 17 ArrayList<FileInputStream> arr=new ArrayList<FileInputStream>(); 18 19 arr.add(new FileInputStream("1.txt")); 20 arr.add(new FileInputStream("2.txt")); 21 arr.add(new FileInputStream("3.txt")); 22 SequenceInputStream ss1=new SequenceInputStream(Collections.enumeration(arr)); 23 /* 24 * Collections.enumeration(arr)的实现原理: 25 * 26 * Enumeration API note:The functionality of this interface is duplicated by the Iterator interface 27 * 翻译:该接口的功能被Iterator接口复制 28 * 29 * final Iterator<FileInputStream> it=arr.iterator(); 30 * SequenceInputStream ss1=new SequenceInputStream(new Enumeration<InputStream>() { 31 @Override 32 public boolean hasMoreElements() { 33 34 return it.hasNext(); 35 } 36 37 @Override 38 public InputStream nextElement() { 39 40 return it.next(); 41 } 42 }); 43 */ 44 byte[] buff=new byte[1024]; 45 FileOutputStream out=new FileOutputStream("4.txt"); 46 int len=0; 47 while((len=ss1.read(buff))!=-1) { 48 out.write(buff,0,len); 49 } 50 out.close(); 51 52 ss1.close(); 53
文件切割实例:
1 public static void splitFile(File file) throws IOException { 2 // 用读取流关联文件 3 FileInputStream fis = new FileInputStream(file); 4 5 // 定义一个1M的缓冲区 6 byte[] buf = new byte[SIZE]; 7 8 // 创建目的 9 FileOutputStream fos = null; 10 11 int len = 0; 12 int count = 1; 13 File dir = new File("partfiles"); 14 15 if (!dir.exists()) { 16 dir.mkdirs(); 17 } 18 19 while ((len = fis.read(buf)) != -1) { 20 fos = new FileOutputStream(new File(dir, (count++) + ".part")); 21 fos.write(buf,0,len); 22 } 23 fos.close(); 24 fis.close(); 25 }