文件切割及合并(配置文件添加)
文件的切割
- 需求分析
- 切割文件时应该要指定将文件切割成多大。
- 切割时应记住源文件是何种类型的,以便于合并时操作。
- 应设置一个配置文件来存储这些信息。
- 代码实现
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();
文件合并
- 需求分析
- 首先应该读取配置文件信息,判断配置信息是否存在并且唯一。
- 若配置信息存在,则获取源文件格式以及切割数量。
- 获取所有切割后文件,并加以判断文件是否有丢失。
- 将所有切割后文件与流相关联,并存入一个集合中。
- 将所有流合并,最终还原。
- 代码实现
配置文件读取及判断
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);
}