文件的切割和合并

package cn.hncu.inOut.io2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;

import javax.swing.JFileChooser;

public class FileSplitDemo {

	public static void main(String[] args) throws IOException{
		//“打开文件”对话框的使用
		JFileChooser jfc = new JFileChooser();
		int result = jfc.showOpenDialog(null);
		File file =null;
		File desDir =null;
		//1切割
		if(result==JFileChooser.APPROVE_OPTION){
			//切割文件
			file = jfc.getSelectedFile();//用户所选择的文件
			//System.out.println(file.getName());
			desDir = new File(file.getParent(),"splitFiles");
			System.out.println(desDir.getAbsolutePath());
			fileSplit(file,desDir);
			
			//2合并(运行时,直接对刚才切割的那些文件碎片进行合并)
			String fileName = file.getName();
			mergeFile(desDir,fileName);
			
		}
		
		
		
	}

	private static void fileSplit(File srcFile, File desDir) throws IOException {
		//1源
		FileInputStream fis = new FileInputStream(srcFile);
		//2目的
		
		//文件io流操作的健壮性防护(用File对象去开道)
		if(!desDir.exists()){
			desDir.mkdirs();
		}
		
		//切割
		FileOutputStream fos = null;
		byte buf[] = new byte[1024*1024];
		int len=0;
		int count=1;
		while( (len=fis.read(buf))!=-1 ){
			String fileName = srcFile.getName()+(count++)+".part";
			fos = new FileOutputStream( new File(desDir,fileName) );
			fos.write(buf,0,len);
			fos.close();
		}
	}
	
	private static void mergeFile(File srcDir, String fileName) throws IOException {
		//健壮性防护(用File对象去开道)
		if(!srcDir.exists()){
			throw new RuntimeException(srcDir.getName()+"不存在");
		}
		File partFiles[] = srcDir.listFiles();
		//测试:输出碎片的文件名
//		for(File f:partFiles){
//			System.out.println(f.getName());
//		}
		if(partFiles.length==0){
			throw new RuntimeException("碎片不存在!");
		}
		
		//用序列流进行文件合并
		ArrayList<FileInputStream> aList = new ArrayList<FileInputStream>();
		for(int i=0;i<partFiles.length;i++){
			aList.add(new FileInputStream( new File(srcDir,fileName+(i+1)+".part")) );
		}
		//枚举接口对象
		Enumeration<FileInputStream> en = Collections.enumeration(aList);
		SequenceInputStream sis = new SequenceInputStream(en);
		
		//把序列流当中的内容写到一个新文件(合并后的文件)
		FileOutputStream fos = new FileOutputStream(new File(srcDir,fileName));
		byte buf[] = new byte[1024];
		int len=0;
		while( (len=sis.read(buf))!=-1){
			fos.write(buf,0,len);
		}
		fos.close();
		sis.close();
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值