Java 獲取Enumeration類型的集合
阿新 • • 發佈:2017-08-12
fin out 通過 ide logs bsp ava while read
學習到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 = newFileInputStream("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 for (int i = -1; (i = sis.read()) != -1;) 34 { 35 os.write(i); 36 }
如果要想操作裏面的元素,也可以使用它的兩個方法
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 }
Java 獲取Enumeration類型的集合