用java分割与合并文件的一个简单示例

转载:[url]http://hi.baidu.com/triceratops/blog[/url]

import java.io.*;

public class SplitAndCombineFile{
private byte[] buffer = new byte[1024];
private int current;

public void split(File file, long threshold) throws IOException{
long fileSize = file.length();
int fileFragmentCount = (int)(fileSize/threshold+1);
long accumulate;
String filePath = file.getAbsolutePath();
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos;
for(int i=0;i<fileFragmentCount;i++){
fos = new FileOutputStream(new File(filePath+".part"+(i+1)));
accumulate = 0;
while((current=fis.read(buffer,0,1024))!=-1){
accumulate+=current;
fos.write(buffer,0,current);
fos.flush();
if(accumulate>=threshold)
break;
}
fos.close();
}
}

public void combine(File targetFile, File partFileFolder) throws IOException{
if(partFileFolder.isFile())
throw new IOException("\""+partFileFolder+"\" is not a file folder!");

FileOutputStream fos = new FileOutputStream(targetFile);
FileInputStream fis;
File[] partFiles = partFileFolder.listFiles();
for(int i=0;i<partFiles.length;i++){
fis = new FileInputStream(partFiles[i]);
while((current=fis.read(buffer,0,1024))!=-1){
fos.write(buffer,0,current);
fos.flush();
}
}
fos.close();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值