美文网首页
IO流之合并流

IO流之合并流

作者: 秃头大叔 | 来源:发表于2017-11-20 11:39 被阅读0次

    SequenceInputStream合并流

    可将多个读取流合并,通常用于大文件切割后的合并;

    文件的分割
    
    import java.io.File;
    import java.io.FileFilter;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.SequenceInputStream;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Enumeration;
    
    public class qiegeAndhebin{
    
        /**
         * @param args
         * @throws IOException 
         */
        public static void main(String[] args) throws IOException {
    //      切割文件
            File dir = new File("hehe");
            if(!dir.exists()){
                dir.mkdir();
            }
            File file = new File("emailcard.bmp");
            FileInputStream fis = new FileInputStream(file);
            FileOutputStream fos = null;
            int len;
            int count = 1;
            byte[] bytes = new byte[2048];
            System.out.println("文件共"+file.length()+"字节,分割成"+file.length()/2048+"个文件");
            while((len = fis.read(bytes)) != -1){  //按照2048字节进行分割文件
                fos = new FileOutputStream(new File(dir,count++ + ".part"));
                fos.write(bytes,0,len);
                fos.flush();
            }
            fos.close();
            fis.close();
            
            
    
    
    文件的合并
            
    //      读取dir目录下所有文件,添加到array集合,
            ArrayList<FileInputStream> array = new ArrayList<FileInputStream>();
            for(int i =0 ; i< dir.listFiles(new hzmFilter("part")).length;i++){
                array.add(new FileInputStream(new File(dir,i+1+".part")));
            }
            Enumeration<FileInputStream> en = Collections.enumeration(array); //枚举
            SequenceInputStream in = new SequenceInputStream(en);//获得合并流,另种传参方式可,直接传入File1,File2,在文件数量及名称已经的情况可用
            FileOutputStream fos1 = new FileOutputStream(new File(dir,"hebin.bmp"));//指定目录创建合并的文件
            int num;
            byte[] bytes1 = new byte[1024];
            while((num = in.read(bytes1)) != -1){
                fos1.write(bytes1,0,num);
                fos1.flush();
            }
            
            fos1.close();
            in.close();
            
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:IO流之合并流

          本文链接:https://www.haomeiwen.com/subject/dtxvvxtx.html