Java 获取Enumeration类型的集合

学习到java的io流中关于序列流SequenceInputStream使用,其中把3个以上的流串联起来操作,

使用的参数是生成运行时类型为 InputStream 对象的 Enumeration 型参数,本人对Enumeration集合

了解较少,便记录一下:

方法一:

    通过Vector集合来获得:

         InputStream is1 = new FileInputStream("d:\\1.txt");
InputStream is2 = new FileInputStream("d:\\2.txt");
InputStream is3 = new FileInputStream("d:\\3.txt");
OutputStream os = new FileOutputStream("d:\\4.txt"); //使用Vector集合获取Enumeration
Vector<InputStream> v = new Vector<InputStream>();
v.add(is1);
v.add(is2);
v.add(is3); Enumeration<InputStream> elem = v.elements(); SequenceInputStream sis = new SequenceInputStream(elem); byte[] buf = new byte[1024]; int len = 0; while((len = sis.read(buf)) != -1)
{
os.write(buf, 0, len);
}

如果要想操作里面的元素,可以使用它的两个方法

 1      //使用Vector集合获取Enumeration
Vector<InputStream> v = new Vector<InputStream>();
v.add(is1);
v.add(is2);
v.add(is3); Enumeration<InputStream> elem = v.elements();

      
while(elem.hasMoreElements())
{
System.out.println(elem.nextElement());
}

方法二:

  利用List集合+Iterator+匿名内部类方法实现

  

         InputStream is1 = new FileInputStream("d:\\1.txt");
InputStream is2 = new FileInputStream("d:\\2.txt");
InputStream is3 = new FileInputStream("d:\\3.txt");
OutputStream os = new FileOutputStream("d:\\4.txt"); LinkedHashSet<InputStream> set = new LinkedHashSet<InputStream>();
set.add(is1);
set.add(is2);
set.add(is3); final Iterator<InputStream> it = set.iterator(); Enumeration<InputStream> en = new Enumeration<InputStream>()
{ @Override
public boolean hasMoreElements()
{
// TODO Auto-generated method stub
return it.hasNext();
} @Override
public InputStream nextElement()
{
// TODO Auto-generated method stub
return it.next();
}
}; SequenceInputStream sis = new SequenceInputStream(en);    byte[] buf = new byte[1024];
           int len = 0;

           while((len = sis.read(buf)) != -1)
{
os.write(buf, 0, len);
}

如果要想操作里面的元素,也可以使用它的两个方法

      Enumeration<InputStream> en = new Enumeration<InputStream>()
{ @Override
public boolean hasMoreElements()
{
// TODO Auto-generated method stub
return it.hasNext();
} @Override
public InputStream nextElement()
{
// TODO Auto-generated method stub
return it.next();
}
}; while(en.hasMoreElements())
{
System.out.println(en.nextElement());
}
上一篇:PacBio软件总览 - 初级分析


下一篇:384. Shuffle an Array