Java 获取Enumeration类型的集合
学习到java的io流中关于序列流SequenceInputStream使用,其中把3个以上的流串联起来操作,
使用的参数是生成运行时类型为 InputStream
对象的 Enumeration
型参数,本人对Enumeration集合
了解较少,便记录一下:
方法一:
通过Vector集合来获得:
1 InputStream is1 = new FileInputStream("d:\\1.txt"); 2 InputStream is2 = new FileInputStream("d:\\2.txt"); 3 InputStream is3 = new FileInputStream("d:\\3.txt"); 4 OutputStream os = new FileOutputStream("d:\\4.txt"); 5 6 //使用Vector集合获取Enumeration 7 Vector<InputStream> v = new Vector<InputStream>(); 8 v.add(is1); 9 v.add(is2); 10 v.add(is3); 11 13 Enumeration<InputStream> elem = v.elements(); 14 15 SequenceInputStream sis = new SequenceInputStream(elem); 16 17 byte[] buf = new byte[1024]; 18 19 int len = 0; 20 21 while((len = sis.read(buf)) != -1) 22 { 23 os.write(buf, 0, len); 24 }
如果要想操作里面的元素,可以使用它的两个方法
1 //使用Vector集合获取Enumeration 2 Vector<InputStream> v = new Vector<InputStream>(); 3 v.add(is1); 4 v.add(is2); 5 v.add(is3); 6 7 8 Enumeration<InputStream> elem = v.elements(); 9
10 while(elem.hasMoreElements()) 11 { 12 System.out.println(elem.nextElement()); 13 }
方法二:
利用List集合+Iterator+匿名内部类方法实现
1 InputStream is1 = new FileInputStream("d:\\1.txt"); 2 InputStream is2 = new FileInputStream("d:\\2.txt"); 3 InputStream is3 = new FileInputStream("d:\\3.txt"); 4 OutputStream os = new FileOutputStream("d:\\4.txt"); 5 6 LinkedHashSet<InputStream> set = new LinkedHashSet<InputStream>(); 7 set.add(is1); 8 set.add(is2); 9 set.add(is3); 10 11 final Iterator<InputStream> it = set.iterator(); 12 13 Enumeration<InputStream> en = new Enumeration<InputStream>() 14 { 15 16 @Override 17 public boolean hasMoreElements() 18 { 19 // TODO Auto-generated method stub 20 return it.hasNext(); 21 } 22 23 @Override 24 public InputStream nextElement() 25 { 26 // TODO Auto-generated method stub 27 return it.next(); 28 } 29 }; 30 31 SequenceInputStream sis = new SequenceInputStream(en); 32 33 byte[] buf = new byte[1024];
int len = 0;
while((len = sis.read(buf)) != -1)
{
os.write(buf, 0, len);
}
如果要想操作里面的元素,也可以使用它的两个方法
1 Enumeration<InputStream> en = new Enumeration<InputStream>() 2 { 3 4 @Override 5 public boolean hasMoreElements() 6 { 7 // TODO Auto-generated method stub 8 return it.hasNext(); 9 } 10 11 @Override 12 public InputStream nextElement() 13 { 14 // TODO Auto-generated method stub 15 return it.next(); 16 } 17 }; 18 19 while(en.hasMoreElements()) 20 { 21 System.out.println(en.nextElement()); 22 }