IO流学习记录(3)——文件的切割以及合并

文件切割及合并(配置文件添加)

文件的切割

  • 需求分析
  1. 切割文件时应该要指定将文件切割成多大。
  2. 切割时应记住源文件是何种类型的,以便于合并时操作。
  3. 应设置一个配置文件来存储这些信息。
  • 代码实现
	FileInputStream fis = new FileInputStream(file);

		byte[] buf = new byte[SIZE];    //定义切割大小

		FileOutputStream fos = null;
		int len = 0;
		int count = 1;

		Properties prop = new Properties();
		
		File dir = new File("F:\\my_work");         //目标路径
		if (dir.exists())
			dir.mkdirs();

		while ((len = fis.read(buf)) != -1) {
			fos = new FileOutputStream(new File(dir, (count++) + ".part"));
			fos.write(buf, 0, len);
			fos.close();
		}
		prop.setProperty("partcount", count + "");
		prop.setProperty("filename", file.getName());

		fos = new FileOutputStream(new File(dir, file.getName() + ".properties"));
		//配置文件创建
		prop.store(fos, "");
		fis.close();
		fos.close();

文件合并

  • 需求分析
  1. 首先应该读取配置文件信息,判断配置信息是否存在并且唯一。
  2. 若配置信息存在,则获取源文件格式以及切割数量。
  3. 获取所有切割后文件,并加以判断文件是否有丢失。
  4. 将所有切割后文件与流相关联,并存入一个集合中。
  5. 将所有流合并,最终还原。
  • 代码实现
    配置文件读取及判断
File[] propertiesfiles = dir.listFiles(new SuffixFiler(".properties"));
		
		if(propertiesfiles.length!=1)
			throw new RuntimeException("该"+dir+"下没有properties文件或者文件不唯一");
		
		File confile = propertiesfiles[0];

获取配置文件信息

		Properties prop = new Properties();
		
		FileInputStream fis = new FileInputStream(confile);
		
		prop.load(fis);
		String filename = prop.getProperty("filename");
		int count = Integer.parseInt(prop.getProperty("count"));

获取所有切割文件并判断

File[] partfiles = dir.listFiles(new SuffixFiler(".part"));
		if(partfiles.length!=(count-1))
			throw new RuntimeException("文件数量错误,无法合并!");

将切割文件存入集合

ArrayList<FileInputStream> list = new ArrayList<FileInputStream>();
		
		for (int i = 0; i < partfiles.length; i++) {
			
			list.add(new FileInputStream(partfiles[i]));
		}

流的合并

Enumeration<FileInputStream> enume = Collections.enumeration(list);

		SequenceInputStream sis = new SequenceInputStream(enume);
		
		FileOutputStream fos = new FileOutputStream(new File(dir, filename));

		byte[] buf = new byte[1024];

		int len = 0;

		while ((len = sis.read(buf)) != -1) {
			fos.write(buf, 0, len);
		}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值