关于JAVA的笔记(切割合并文件)

切割文件

public static void splitfile(File resFile, File splitDir) throws IOException {
	// TODO Auto-generated method stub
	if(!splitDir.exists()) {
		splitDir.mkdirs(); //防止路径不存在
	}
	//思路:1个输入流,n个输出流
	
	InputStream in=new FileInputStream(resFile);//将文件导入内存
	OutputStream out=null;
	int number=0;//标识数量
	byte[] buf=new byte[1024*1024];//定义缓冲区大小 以切割文件大小来处理。
	int len=-1;//标识in指针
	while((len=in.read(buf))!=-1) {
		
	out=new FileOutputStream(new File(splitDir,resFile.getName().substring(0, resFile.getName().indexOf(".")).concat("_")+ number++ +".part"));//生成格式为“源文件名_number.part” 格式的文件
		out.write(buf, 0, len);
		out.close();
	}
	in.close();
	
}

为了未来合并方便那么可以生成多个配置文件保留文件名以及分割数量。(优化1)

System.out.println("输出完成共输出:"+number+"个文件");
	out=new FileOutputStream(new File(splitDir,number+".config"));
	String linenext=System.getProperty("line.separator");//获取系统换行符
	out.write(("filename="+resFile.getName()).getBytes());
	out.write(linenext.getBytes());//将字符串换行处理
	out.write(("partcount="+(number-1)).getBytes());
	out.close();
	in.close();

采用property文件来放配置文件(优化2)

out=new FileOutputStream(new File(splitDir,resFile.getName().substring(0, resFile.getName().indexOf("."))+".config"));
	Properties pro=new Properties();
	pro.setProperty("filename", resFile.getName());
	pro.setProperty("partcount",String.valueOf(number-1));
		pro.store(out, "文件配置");//保存
	out.close();

合并:

  1. 读取配置文件中的参数。
public static void mergefile(File path, File configname) throws IOException {
		// TODO Auto-generated method stub
		List<InputStream> inputs=new ArrayList<InputStream>();
		InputStream in=new FileInputStream(configname);
		Properties pro=new Properties();
		pro.load(in);
		String name=pro.getProperty("filename");
		String number=pro.getProperty("partcount");
		int a=Integer.parseInt(number);
		in.close();
  1. 将文件分别读入输入流
for(int i=0;i<=a;i++) {
				inputs.add(new FileInputStream(new File(path,name.substring(0
					, name.indexOf(".")).concat("_"+i+".part"))));
						System.out.println("添加入List中");
		}
  1. 拼接输入流
    (通过Collections工具类将List转化为Enumeration类型(特旧版本))
	Enumeration<FileInputStream> en=Collections.enumeration(inputs); 
		SequenceInputStream sequenceInputStream=new SequenceInputStream(en);
  1. 输出
	int len=-1;
		
		OutputStream out=new FileOutputStream(path+"\\new"+name);
		while((len=sequenceInputStream.read(buf))!=-1) {
			out.write(buf,0,len);
					}
		out.close();
		sequenceInputStream.close();
		System.out.println("合并完成");
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值