1. 程式人生 > >大檔案的分塊與合併

大檔案的分塊與合併

import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
* @author Administrator
* @version 1.0
**/
public class TestFile {



//測試檔案分塊
@Test
public void testChunk() throws IOException {
//原始檔
File sourceFile = new File("D:\\lucene.avi");
//塊檔案目錄
String chunkFileFolder = "D:\\chunks";

//先定義塊檔案大小
long chunkFileSize = 1 * 1024 * 1024;

//塊數
long chunkFileNum = (long) Math.ceil(sourceFile.length() * 1.0 /chunkFileSize);

//建立讀檔案的物件
RandomAccessFile raf_read = new RandomAccessFile(sourceFile,"r");

//緩衝區
byte[] b = new byte[1024];
for(int i=0;i<chunkFileNum;i++){
//塊檔案
File chunkFile = new File(chunkFileFolder+i);
//建立向塊檔案的寫物件
RandomAccessFile raf_write = new RandomAccessFile(chunkFile,"rw");
int len = -1;

while((len = raf_read.read(b))!=-1){

raf_write.write(b,0,len);
//如果塊檔案的大小達到 1M開始寫下一塊兒
if(chunkFile.length()>=chunkFileSize){
break;
}
}
raf_write.close();


}
raf_read.close();
}


//測試檔案合併
@Test
public void testMergeFile() throws IOException {
//塊檔案目錄
String chunkFileFolderPath = "D:\\chunks";
//塊檔案目錄物件
File chunkFileFolder = new File(chunkFileFolderPath);
//塊檔案列表
File[] files = chunkFileFolder.listFiles();
//將塊檔案排序,按名稱升序
List<File> fileList = Arrays.asList(files);
Collections.sort(fileList, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
if(Integer.parseInt(o1.getName())>Integer.parseInt(o2.getName())){
return 1;
}
return -1;
}
});

//合併檔案
File mergeFile = new File("D:\\lucene_merge.avi");
//建立新檔案
boolean newFile = mergeFile.createNewFile();

//建立寫物件
RandomAccessFile raf_write = new RandomAccessFile(mergeFile,"rw");

byte[] b = new byte[1024];
for(File chunkFile:fileList){
//建立一個讀塊檔案的物件
RandomAccessFile raf_read = new RandomAccessFile(chunkFile,"r");
int len = -1;
while((len = raf_read.read(b))!=-1){
raf_write.write(b,0,len);
}
raf_read.close();
}
raf_write.close();
}
}