Java 檔案拆分合並工具類
阿新 • • 發佈:2018-11-23
/**
* 拆分的思路,先把原始檔的所有內容讀取到記憶體中,然後從記憶體中挨個分到子檔案裡
*
* @param srcFile
* 要拆分的原始檔 路徑
* @param eachSize
* 按照這個大小,拆分 100 * 1024; // 100k
*/
private static void splitFile(File srcFile, int eachSize) {
if (0 == srcFile.length())
throw new RuntimeException("檔案長度為0,不可拆分");
byte[] fileContent = new byte[(int) srcFile.length()];
// 為了在finally中關閉,需要宣告在try外面
FileInputStream fis = null;
try {
fis = new FileInputStream(srcFile);
fis.read(fileContent);
} catch (IOException e) {
e.printStackTrace();
} finally {
// 在finally中關閉
try {
if(null!=fis)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
int fileNumber;
if (0 == fileContent.length % eachSize)
fileNumber = (int ) (fileContent.length / eachSize);
else
fileNumber = (int) (fileContent.length / eachSize) + 1;
for (int i = 0; i < fileNumber; i++) {
String eachFileName = srcFile.getName() + "-" + i;
File eachFile = new File(srcFile.getParent(), eachFileName);
byte[] eachContent;
if (i != fileNumber - 1)
eachContent = Arrays.copyOfRange(fileContent, eachSize * i, eachSize * (i + 1));
else
eachContent = Arrays.copyOfRange(fileContent, eachSize * i, fileContent.length);
// 為了在finally中關閉,宣告在try外面
FileOutputStream fos = null;
try {
fos = new FileOutputStream(eachFile);
fos.write(eachContent);
System.out.printf("輸出子檔案%s,其大小是%,d位元組%n", eachFile.getAbsoluteFile(), eachFile.length());
} catch (IOException e) {
e.printStackTrace();
} finally {
// finally中關閉
try {
if(null!=fos)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 合併的思路,就是從eclipse.exe-0開始,讀取到一個檔案,就開始寫出到 eclipse.exe中,直到沒有檔案可以讀
*
* @param folder
* 需要合併的檔案所處於的目錄
* @param fileName
* 需要合併的檔案的名稱
* @throws FileNotFoundException
*/
private static void murgeFile(String folder, String fileName) {
File destFile = new File(folder, fileName);
// 使用try-with-resource的方式自動關閉流
try (FileOutputStream fos = new FileOutputStream(destFile);) {
int index = 0;
while (true) {
File eachFile = new File(folder, fileName + "-" + index++);
if (!eachFile.exists())
break;
// 使用try-with-resource的方式自動關閉流
try (FileInputStream fis = new FileInputStream(eachFile);) {
byte[] eachContent = new byte[(int) eachFile.length()];
fis.read(eachContent);
fos.write(eachContent);
fos.flush();
}
System.out.printf("把子檔案 %s寫出到目標檔案中%n", eachFile);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.printf("最後目標檔案的大小:%,d位元組", destFile.length());
}
推薦學習地址點選這裡