黑马程序员技术交流社区

标题: IO合并文件 使用ArrayList 复写Enumeration 内的方法体 [打印本页]

作者: fmi110    时间: 2015-8-8 14:35
标题: IO合并文件 使用ArrayList 复写Enumeration 内的方法体
IO
  1. class  
  2. {
  3.         public static void main(String[] args)
  4.         {
  5.                 merge();
  6.                 System.out.println("Hello World!");
  7.         }
  8.         public static void merge() throws IOException
  9.         {
  10.                 //集合接受流
  11.                 ArrayList<FileInputStream> ar = new ArrayList<FileInputStream>();
  12.                 //添加要合并的文件
  13.                 ar.add(new FileInputStream("d:\\1.part"));
  14.                 ar.add(new FileInputStream("d:\\2.part"));
  15.                 //创建输出流
  16.                 FileOutputStream fos = null;

  17.                 final Iterator<FileInputStream> it = ar.iterator();//为保证传递给内部类后数据的一致性,用final修饰

  18.                 //复写枚举,并传递给SequenceInputStream
  19.                 Enumeration<FileInputStream> en = new Enumeration<FileInputStream>(){
  20.                         public boolean hasMoreElements(){
  21.                                 return it.hasNext();
  22.                         }
  23.                         public FileInputStream nextElement(){
  24.                                 return it.next();
  25.                         }
  26.                 };

  27.                 SequenceInputStream sis = new SequenceInputStream(en);
  28.                 //缓冲
  29.                 byte[] buf = new byte[1024*1024];
  30.                 int len;
  31.                 fos = new FileOutputStream("d:\\mergeFile.jpg");
  32.                 while((len=sis.read(buf))!=-1){
  33.                         fos.write(buf,0,len);
  34.                         fos.flush();
  35.                 }
  36.                 fos.close();
  37.                 sis.close();
  38.         }
  39. }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2