/**********************************************
* 功能:将文件的切割和合并与Properties相结合使用
* 作者:khq
* 时间:2020年4月22日
**********************************************/
package FileOperation;
import java.io.File;
import java.io.FileInputStream;
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 java.util.Properties;
public class FileSpliteCombineWithProperties {
public static void main(String[] args) throws Exception {
File f1 = new File("D:\\worFile\\JavaFile\\FileTest");
File f2 = new File(f1,"dsk.bmp");
getFileSplite(f2);
getFileCombine(f1);
}
//文件切割阶段,其实就是每次都读取一定大小的内容,然后将读取到的内容写到新的文件当中
public static void getFileSplite(File fe) throws IOException {
//将文件与读取流相关联
FileInputStream fis = new FileInputStream(fe);
byte[] be = new byte[512*1024]; //大小0.5M
int len = 0;
int count = 1;
FileOutputStream fos = null;
while((len = fis.read(be))!=-1) {
fos = new FileOutputStream((count++)+".part");
fos.write(be, 0, len);
fos.close(); //每次写完,都要关闭
}
fis.close();
FileOutputStream fops = new FileOutputStream(new File(count+".properties"));
Properties prop = new Properties();
prop.setProperty("filetype", ".bmp");
prop.setProperty("fileSplite", count+"");
prop.store(fops,"filetype:fileSplite");
fops.close();
}
//将指定目录下的文件进行合并
public static void getFileCombine(File dir) throws IOException {
//先寻找配置文件
File[] fe = dir.listFiles(new Sufferix(".properties")); //按照后缀名对文件过滤
if(fe.length!=1) {
System.out.println("配置文件不存在或者不唯一.");
System.exit(-1);
}
Properties props = new Properties();
props.load(new FileInputStream(fe[0]));
int count = Integer.parseInt(props.getProperty("fileSplite"));
String fileType = props.getProperty("filetype");
File[] fle = dir.listFiles(new Sufferix(".part"));
if(fle.length!=(count-1)) {
System.out.println("当前目录下的碎片文件有所缺失或过多,不符合要求,无法继续合并");
System.exit(-1);
}
ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
for(int i=0;i<count-1;i++) {
al.add(new FileInputStream(fle[i]));
}
Enumeration<FileInputStream> en = Collections.enumeration(al);
SequenceInputStream sis = new SequenceInputStream(en);
FileOutputStream fops = new FileOutputStream("newFile"+fileType);
byte[] bt = new byte[1024];
int len =0;
while((len=sis.read(bt))!=-1) {
fops.write(bt,0,len);
fops.flush();
}
sis.close();
fops.close();
}
}
定义文件名过滤器:
package FileOperation;
import java.io.File;
import java.io.FilenameFilter;
public class Sufferix implements FilenameFilter {
private String myName;
Sufferix(String myName){
this.myName = myName;
}
@Override
public boolean accept(File dir, String name) { //找到目录dir下,文件名是myName的文件
return name.endsWith(myName);
}
}
结果: