IO流_SequenceInputStream(序列流)

SequenceInputStream(序列流):就是将多个流合成一个有序的流

 

需求:将三个文件中的数据合并到一个文件中

 1 import java.io.FileInputStream;

 2 import java.io.FileOutputStream;

 3 import java.io.IOException;

 4 import java.io.SequenceInputStream;

 5 import java.util.Enumeration;

 6 import java.util.Vector;

 7 

 8 public class SequenceInputStreamDemo {

 9     public static void main(String[] args) throws IOException {

10         

11         //该集合效率低,所以用ArrayList集合,但是该集合没有枚举,所以要自定义一个枚举

12         Vector<FileInputStream> v = new Vector<FileInputStream>();

13         

14         v.add(new FileInputStream("F:\\0.txt"));

15         v.add(new FileInputStream("F:\\a.txt"));

16         v.add(new FileInputStream("F:\\info.txt"));

17         

18         Enumeration<FileInputStream> en = v.elements();

19         

20         SequenceInputStream sis = new SequenceInputStream(en);

21         

22         FileOutputStream fos = new FileOutputStream("F:\\feng.txt");

23         

24         byte[] buf = new byte[1024];

25         int len = 0;

26         while((len=sis.read(buf))!=-1){

27             fos.write(buf,0,len);

28         }

29         

30         sis.close();

31         fos.close();

32     }

33 

34 }

 

 1 import java.io.FileInputStream;

 2 import java.io.FileOutputStream;

 3 import java.io.IOException;

 4 import java.io.SequenceInputStream;

 5 import java.util.ArrayList;

 6 import java.util.Collections;

 7 import java.util.Enumeration;

 8 import java.util.Iterator;

 9 

10 public class SequenceInputStreamDemo {

11     public static void main(String[] args) throws IOException {

12         ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();

13         al.add(new FileInputStream("F:\\0.txt"));

14         al.add(new FileInputStream("F:\\a.txt"));

15         al.add(new FileInputStream("F:\\info.txt"));

16         

17         Enumeration<FileInputStream> en = Collections.enumeration(al);//该方法的原理就是下面自定义的枚举

18         /*

19         

20         final Iterator<FileInputStream> it = al.iterator();

21         //自定义枚举,与ArrayList的迭代器结合使用

22         Enumeration<FileInputStream> en = new Enumeration<FileInputStream>() {

23             @Override

24             public boolean hasMoreElements() {

25                 return it.hasNext();

26             }

27             @Override

28             public FileInputStream nextElement() {

29                 return it.next();

30             }

31         };

32         */

33         

34         SequenceInputStream sis = new SequenceInputStream(en);

35         

36         FileOutputStream fos = new FileOutputStream("F:\\jian.txt");

37         

38         byte[] buf = new byte[1024];

39         int len = 0;

40         while((len=sis.read(buf))!=-1){

41             fos.write(buf,0,len);

42         }

43         

44         sis.close();

45         fos.close();

46             

47     }

48 

49 }

 

你可能感兴趣的:(IO流_SequenceInputStream(序列流))