import java.io.*;
import java.util.*;
public class Main{
/* 文件切割 */
private static final int SIZE = 1024*1024;
public static void splitFile(File file) throws IOException {
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[SIZE]; //切成n块SIZE大小
FileOutputStream fos = null;
int len = 0;
int cnt = 1;
/*使用properties记录切割文件产生的个数和被切割文件的名称,方便合并时使用 */
Properties prop = new Properties();
File partDir = new File("C:\\partFiles");
if(!partDir.exists())
partDir.mkdir();
while((len = fis.read(buffer)) != -1) {
fos = new FileOutputStream(new File(partDir,(cnt++)+".part")); //自定义碎片文件后缀.part
fos.write(buffer,0,len);
fos.close();
}
//将切割文件信息保存在Properties中
prop.setProperty("partNum", cnt+"");
prop.setProperty("fileName", file.getName());
fos = new FileOutputStream(new File(partDir,(cnt++)+".properties"));
prop.store(fos, "");//将properties集合中的信息存储到文件中。
fos.close();
fis.close();
}
/* 合并碎片文件 */
public static void mergeFile(File dir) throws IOException {
File[] files = dir.listFiles(new SuffixFilter(".properties"));
if(files.length != 1)
throw new RuntimeException(dir+"配置文件不存在或配置文件重复");
//记录配置文件信息
File confile = files[0];
//获取该文件信息
Properties prop = new Properties();
FileInputStream fis = new FileInputStream(confile);
prop.load(fis);
//获取prop中的信息
String fileName = prop.getProperty("filename");
int cnt = Integer.parseInt(prop.getProperty("partNum"));
//获取该文件夹下所有碎片,统计个数
File[] partFiles = dir.listFiles(new SuffixFilter(".part"));
if(partFiles.length != (cnt-1))
throw new RuntimeException("碎片个数不对,应为"+cnt+"个");
//添加集合
ArrayList<FileInputStream> a1 = new ArrayList<FileInputStream>();
for(int i=0; i<partFiles.length; i++)
a1.add(new FileInputStream(files[i]));
Enumeration<FileInputStream> en = Collections.enumeration(a1);
SequenceInputStream sis = new SequenceInputStream(en);
FileOutputStream fos = new FileOutputStream(new File(dir,fileName));
byte[] buffer = new byte[1024*1024];
int len = 0;
while((len = sis.read(buffer)) != -1) {
fos.write(buffer,0,len);
}
fos.close();
sis.close();
}
public static void main(String[] args) throws IOException {
splitFile(new File("D:\\demo4.txt"));
mergeFile(new File("C:\\partFiles"));
}
}
class SuffixFilter implements FilenameFilter {
private String suffix;
public SuffixFilter(String suffix) {
super();
this.suffix = suffix;
}
@Override
public boolean accept(File dir, String name) {
return name.endsWith(suffix);
}
}