切割文件
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();
合并:
- 读取配置文件中的参数。
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();
- 将文件分别读入输入流
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中");
}
- 拼接输入流
(通过Collections工具类将List转化为Enumeration类型(特旧版本))
Enumeration<FileInputStream> en=Collections.enumeration(inputs);
SequenceInputStream sequenceInputStream=new SequenceInputStream(en);
- 输出
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("合并完成");
}