这是我自己做的文件合并与切割,亲可以看一下。。。。。。。
//将指定文件分割成指定的份数
private static void divide(String src ,int m) {
long start =System. currentTimeMillis();
//目标文件
File file=new File (src);
if(file .isFile()){
//文件的长度
int l =(int )file. length();
//获取目标目标文件的名字
String filename=file .getName() ;
//System.out.println(filename);
//每一份文件的长度
int L =l/ m;
//获取截取之后的文件的名字
String parentName=file .getParent() ;
String beforName=filename .substring( 0, filename.lastIndexOf( "."));
String endName=filename .substring( filename.indexOf (".")) ;
//System.out.println(parentName);
// System.out.println(beforName);
// System.out.println(endName);
//创建流对象
BufferedInputStream bi=null;
BufferedOutputStream bo=null;
try {
bi =new BufferedInputStream( new FileInputStream(file ));
byte[] bytes=new byte [1024* 1024];
int len =-1;
for (int i = 1; i <=m; i++) {
String name=parentName +File. separator+beforName +"_"+ i+endName ;
File file2=new File (name);
bo =new BufferedOutputStream( new FileOutputStream(file2 ));
//开始读写了
while((len =bi. read(bytes ))!=-1 ){
bo .write(bytes, 0, len );
if (file2. length()> L) {
break;
}
bo .flush() ;
}
}
} catch (IOException e) {
e .printStackTrace() ;
}finally{
if (bo!= null) {
try {
bo .close() ;
} catch (IOException e) {
e .printStackTrace() ;
}
}
if (bi!= null) {
try {
bi .close() ;
} catch (IOException e) {
e .printStackTrace() ;
}
}
long end =System. currentTimeMillis();
System .out. println("分割时间为:" +(end -start)) ;
System .out. println("分割完成!" );
}
}
}
//将指定份数的文件合并为一个文件
private static void append(String ...name) {
//获取目标文件
int n =name. length;
//要写入的目标文件的名字
String beforName=name [0].substring (0, name[0].indexOf ("_")) ;
String endName=name [0].substring (name[0].indexOf (".")) ;
StringBuffer fileName=new StringBuffer ();
fileName .append( beforName). append(endName );
File file=new File (fileName. toString());
//System.out.println(fileName);
//创建流对象
BufferedInputStream bi=null;
BufferedOutputStream bo=null;
try {
bo =new BufferedOutputStream( new FileOutputStream(file ,true ));//追加
for (int i = 0; i < name. length; i ++) {
File file1=new File (name[i]);
bi =new BufferedInputStream( new FileInputStream(file1 ));
//开始读写
byte[] bytes=new byte [1024* 1024];
int len =-1;
while((len =bi. read(bytes ))!=-1 ){
bo. write(bytes , 0, len);
bo. flush();
}
}
} catch (IOException e) {
e .printStackTrace() ;
}finally{
if (bo!= null) {
try {
bo .close() ;
} catch (IOException e) {
e .printStackTrace() ;
}
}if (bi!= null) {
try {
bi .close() ;
} catch (IOException e) {
e .printStackTrace() ;
}
}
}
System .out. println("合并完成!" );
}
|