本文共 2259 字,大约阅读时间需要 7 分钟。
//IO流切割文件import java.io.*;import java.util.*;class SplitFile{ public static void main(String[] args) { //splitFile(); merge(); } public static void merge() throws IOException//合并方法 { ArrayListal = new ArrayList ();//ArrayList比Vector效率高,不是线程同步 for (int x = 1;x<=3 ;x++ )//添加流对象中 { al.add(new FileInputStream("c:\\splitfiles\\"+x+".part")) } final Iterator it= al.iterator();//迭代器,因为要被匿名内部类获取 所以必须加final修饰, /*当 变量是final时,若是引用类型,由于其引用值不变(即:永远指向同一个对象),因而:其复制品与原始的引用变量一样,永远指向同一个对象(由于是 final,从而保证:只能指向这个对象,再不能指向其它对象*/ Enumeration en = new Enumeration ()//枚举,匿名内部类 来转换Iterator为Enumeration { public boolean hasMoreElements()//重写方法 判断是否有下一个 { return it.hasNext();//Enumeration对应Iterator的方法 判断是否有下一个 } public FileInputStream nextElement()//重写方法 返回类型FileInputStream /* nextElement() 下一个元素。 一般有hasMoreElements(),如果有下一个元素,那么就用nextElement()取出下一个元素。 一般是枚举中有这个。 public interface Enumeration 实现 Enumeration 接口的对象,它生成一系列元素,一次生成一个。连续调用 nextElement 方法将返回一系列的连续元素。 例如,要输出向量 v 的所有元素,可使用以下方法: for (Enumeration e = v.elements() ; e.hasMoreElements() ; ) { System.out.println(e.nextElement()); } */ { return it.next();//next()遍历方法,返回下一个 } }; SequenceInputStream sis = new SequenceInputStream(en);//参数必须接收Enumeration FileOutputStream fos = new FileOutputStream("c:\\splitfiles\\0.bmp"); byte[] buf = new byte[1024]; int len = 0; while ((len=sis.read(buf))!=-1)//接收sis,循环判断条件,len=sis读取buf不为-1,没到结尾,表示缓冲区不为末尾 { fos.write(buf,0,len);//写入fos;write(byte[] b, int off, int len)就是将数组 b 中的 len 个字节按顺序写入输出流 } fos.close(); sis.close(); } public static void splitFile() throws IOException//分割方法 { //System.out.println("Hello World!"); FileInputStream fis = new FileINputStream("c:\\1.bmp");//关联文件,输入流 FileOutputStream fos = null;//输出流 byte[] buf = new byte[1024*1024];//数组缓冲区大小1M int len = 0; int count = 1; while ((len= fis.read(buf))!=-1)//不等于-1表示 没有读完,连续执行下面{}的语句 { fos = new FileOUtputStream("c:\\splitfiles\\"+(count++)+".part"); fos.write(buf,0,len);//write(数组,下标,长度),len默认为0,表示全部 fos.close(); } fis.close(); }}
转载地址:http://rwzvb.baihongyu.com/