示例代码:
public class FileSpiltDemo {
static int SIZE= 1024*1024;
public static void main(String[] args) throws IOException {
// splitFile(new File("d:\\2.mp4"),new File("d:\\partFiles"));
mergeFile(new File("d:\\partFiles"));
}
//切割文件
public static void splitFile(File file ,File desDir) throws IOException{
if(!desDir.exists()){
desDir.mkdirs();
}
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = null;
byte[] buff = new byte[SIZE];
int count = 1;
int len = 0;
while((len=fis.read(buff))!=-1){
fos = new FileOutputStream(new File(desDir,count+".part"));
fos.write(buff,0,len);
count++;
}
fis.close();
fos.close();
}
//合并文件
public static void mergeFile(File dir) throws IOException{
List<FileInputStream> list = new ArrayList<FileInputStream>();
File[] files = dir.listFiles(new FilenameFilter(){
public boolean accept(File dir, String name) {
return name.endsWith(".part");
}
});
for(File f : files){
list.add(new FileInputStream(f));
}
Enumeration<FileInputStream> en = Collections.enumeration(list);
SequenceInputStream sis = new SequenceInputStream(en);
FileOutputStream fos = new FileOutputStream(new File(dir,"1.mp4"));
byte[] buff = new byte[1024];
int len = 0;
while((len = sis.read(buff))!=-1){
fos.write(buff, 0, len);
}
fos.close();
sis.close();
}
}