IO流切割文件

26 篇文章 0 订阅
//IO流切割文件
import java.io.*;
import java.util.*;
class  SplitFile
{
    public static void main(String[] args) 
    {
        //splitFile();
        merge();
    }

    public static void merge() throws IOException//合并方法
    {
        ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();//ArrayList比Vector效率高,不是线程同步
        for (int x = 1;x<=3 ;x++ )//添加流对象中
        {
            al.add(new FileInputStream("c:\\splitfiles\\"+x+".part"))
        }

        final Iterator<FileInputStream> it= al.iterator();//迭代器,因为要被匿名内部类获取 所以必须加final修饰,
        /*当 变量是final时,若是引用类型,由于其引用值不变(即:永远指向同一个对象),因而:其复制品与原始的引用变量一样,永远指向同一个对象(由于是 final,从而保证:只能指向这个对象,再不能指向其它对象*/

        Enumeration<FileInputStream> en = new Enumeration<FileInputStream>()//枚举,匿名内部类 来转换Iterator为Enumeration
        {
            public boolean hasMoreElements()//重写方法 判断是否有下一个
            {
                return it.hasNext();//Enumeration对应Iterator的方法 判断是否有下一个
            }
            public FileInputStream nextElement()//重写方法 返回类型FileInputStream
            /*
            nextElement() 下一个元素。
            一般有hasMoreElements(),如果有下一个元素,那么就用nextElement()取出下一个元素。
            一般是枚举中有这个。
            public interface Enumeration<E>
            实现 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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值