Posted on 2009-05-24 21:31
啥都寫點 閱讀(230)
評論(0) 編輯 收藏 所屬分類:
J2SE
關鍵技術:
- 分割文件時,指定小文件的長度(字節數),根據File的length方法獲得大文件的長度,以確定目標小文件的數目。用文件輸入流順序地讀取大文件的數據,將數據分流到每個小文件的輸出流中。
- 合并文件時,讀取每個小文件的輸入流,將所有的內容按順序寫入到目標大文件的輸出流中。
package book.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* 文件分割合并器,將大文件分割成若干小文件;將多個小文件合并到一個大文件。
*/
public class FileDivisionUniter {
//分割后的文件名后綴
public static final String SUFFIX = ".pp";
/**
* 分割文件
* @param fileName 待分割的文件名
* @param size 小文件的大小,單位字節
* @return 分割成的小文件的文件名
* @throws Exception
*/
public static String[] divide(String fileName, long size) throws Exception {
File inFile = new File(fileName);
if (!inFile.exists() || (!inFile.isFile())) {
throw new Exception("指定文件不存在!");
}
//獲得被分割文件父文件,將來被分割成的小文件便存在這個目錄下
File parentFile = inFile.getParentFile();
// 取得文件的大小
long fileLength = inFile.length();
if (size <=0){
size = fileLength / 2;
}
// 取得被分割后的小文件的數目
int num = (fileLength % size != 0) ? (int)(fileLength / size + 1)
: (int)(fileLength / size);
// 存放被分割后的小文件名
String[] outFileNames = new String[num];
// 輸入文件流,即被分割的文件
FileInputStream in = new FileInputStream(inFile);
// 讀輸入文件流的開始和結束下標
long inEndIndex = 0;
int inBeginIndex = 0;
//根據要分割的數目輸出文件
for (int outFileIndex = 0; outFileIndex < num; outFileIndex++) {
//對于前num - 1個小文件,大小都為指定的size
File outFile = new File(parentFile, inFile.getName()
+ outFileIndex + SUFFIX);
// 構建小文件的輸出流
FileOutputStream out = new FileOutputStream(outFile);
//將結束下標后移size
inEndIndex += size;
inEndIndex = (inEndIndex > fileLength) ? fileLength : inEndIndex;
// 從輸入流中讀取字節存儲到輸出流中
for (; inBeginIndex < inEndIndex; inBeginIndex++) {
out.write(in.read());
}
out.close();
outFileNames[outFileIndex] = outFile.getAbsolutePath();
}
in.close();
return outFileNames;
}
/**
* 合并文件
* @param fileNames 待合并的文件名,是一個數組
* @param TargetFileName 目標文件名
* @return 目標文件的全路徑
* @throws Exception
*/
public static String unite(String[] fileNames, String TargetFileName)
throws Exception {
File inFile = null;
//構建文件輸出流
File outFile = new File(TargetFileName);
FileOutputStream out = new FileOutputStream(outFile);
for (int i = 0; i < fileNames.length; i++) {
// 打開文件輸入流
inFile = new File(fileNames[i]);
FileInputStream in = new FileInputStream(inFile);
// 從輸入流中讀取數據,并寫入到文件數出流中
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
in.close();
}
out.close();
return outFile.getAbsolutePath();
}
public static void main(final String[] args) throws Exception {
//分割文件
String fileName = "C:/temp/temp.xls";
long size = 1000;
String[] fileNames = FileDivisionUniter.divide(fileName, size);
System.out.println("分割文件" + fileName + "結果:");
for (int i=0; i<fileNames.length; i++){
System.out.println(fileNames[i]);
}
//合并文件
String newFileName = "C:/temp/newTemp.xls";
System.out.println("合并文件結果:" +
FileDivisionUniter.unite(fileNames, newFileName));
}
}
--
學海無涯