文件的分割与合并

来源:互联网 发布:路书什么软件好 编辑:程序博客网 时间:2024/06/10 19:54
//分割文件
    public    void PartFile(File file,String file2) throws IOException{
   
    //定义一个Properties对象,用来创建一个配置文件,存放信息。
    Properties prop = new Properties();
   
    //读取输入流对象源文件
    FileInputStream fis = new FileInputStream(file);
    //定义一个1M缓冲区
    byte[] buf = new byte[SIZE];
    int len =0;
    File dir = new File(file2);
    if(!dir.exists()){
    dir.mkdirs();
    }
    FileOutputStream fos = null;
    int count =1;
    while((len = fis.read(buf)) != -1){
    fos = new FileOutputStream(new File(dir,(count++)+".part"));
    fos.write(buf, 0, len);
    fos.close();
    }
    prop.setProperty("count", count+"");
    prop.setProperty("filename", file.getName());
    File confg = new File(dir,count+".properties");
    FileOutputStream fs = new FileOutputStream(confg);
    prop.store(fs, "file info");
    fos.close();
    fis.close();
    }
    
    //合并文件
    public    void MergeFile(File file) throws IOException{
    //定义一个过滤器,来获取配置文件
    File[] properFile = file.listFiles(new suffixflter(".properties"));
    if(properFile.length != 1){
    throw new RuntimeException("对不起,你的配置文件不存在或者不是唯一的。");
    }
    File dir = properFile[0];
    FileInputStream fos = new FileInputStream(dir);
    Properties prop = new Properties();
    prop.load(fos);
    int count = Integer.parseInt(prop.getProperty("count"));
    String filename = prop.getProperty("filename");
   
    ArrayList<FileInputStream> list = new ArrayList<FileInputStream>();
    for(int i = 1;i< count;i++){
    list.add(new FileInputStream(new File(file,i+".part")));
    }
    Enumeration<FileInputStream> en = Collections.enumeration(list);
   
    SequenceInputStream sis = new SequenceInputStream(en);
    byte[] by = new byte[1024*1024];
    int len  = 0;
    FileOutputStream out = new FileOutputStream(new File(file,filename));
    while((len = sis.read(by)) != -1){
    out.write(by, 0, len);
    }
    out.close();
    sis.close();
    }
0 0
原创粉丝点击