切割大文件与合并文件

题目:将一个大文件切割成指定大小的小文件。最后再将其合并

  切割文件思路:1.明确要切割成后每个文件的大小

     2.当写入指定大小的内容后,新建一个流接着写入文件。

  

public static void cutFile() throws IOException
    {
        File f = new File("D:\\Java\\工具包\\Eclipse安装包\\eclipse-jee-luna-R-win32.zip");
        
        //分割后每个每个文件的大小为100M
        long oneSize = 100*1024*1024;
        
        //读取文件
        FileInputStream bis = new FileInputStream(f);
        
        byte[] buff = new byte[1024*1024];
        int len = 0;
        
        int i=1;
        
        FileOutputStream fos = new FileOutputStream("D:\\eclipse.rar.part"+i);  //第一个流
        
        long max = oneSize;
        while((len = bis.read(buff))!=-1)
        {
            fos.write(buff,0,len);
            max -= len;  
            
            if(max<=0)  //判断文件大小是否达到100M(指定大小)
            {
                fos = new FileOutputStream("D:\\eclipse.rar.part"+(++i));
                max = oneSize;(因为流已经是新的了,文件大小应该重置为100M)
            }
        }
        System.out.println("切割完毕...");
        
        bis.close();
        fos.close();
    }

合并文件使用 SequenceInputStream 就OK了,但是不要用 Vector,效率太低了,可以使用ArrayList

public static void heBin() throws IOException
    {
        ArrayList<FileInputStream> arr = new ArrayList<FileInputStream>();
        
        for(int i=1;i<4;i++)
        {
            arr.add(new FileInputStream("D:\\eclipse.rar.part"+i));
        }
        
        Iterator<FileInputStream> it = arr.iterator();
        
        Enumeration<FileInputStream> en = new Enumeration<FileInputStream>()
        {
            public boolean hasMoreElements()
            {
                return it.hasNext();
            }
            
            public FileInputStream nextElement()
            {
                return it.next();
            }
        };
        
        SequenceInputStream sis = new SequenceInputStream(en);
        byte[] buff = new byte[1024*1024];
        
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\eclipseAll.rar"));
        
        int len = 0;
        
        while((len=sis.read(buff))!=-1)
        {
            bos.write(buff,0,len);
            bos.flush();
        }
        
        System.out.println("合并完成...");
        
        sis.close();
        bos.close();
        
    }

 

posted @ 2017-12-23 18:17  always1024ccnn  阅读(499)  评论(0编辑  收藏  举报