1. 程式人生 > >編寫一個檔案分割工具,能把一個大檔案分割成多個小的檔案。並且能再次把他們合併起來得到完整的檔案

編寫一個檔案分割工具,能把一個大檔案分割成多個小的檔案。並且能再次把他們合併起來得到完整的檔案

package wenjian;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

//編寫一個檔案分割工具,能把一個大檔案分割成多個小的檔案。並且能再次把它們合併起來得到完整的檔案
public class CutFile {
    public static void main(String[] args) {
        //呼叫cutFile()函式 傳人蔘數分別為 (原大檔案,切割後存放的小檔案的路徑,切割規定的記憶體大小)
cutFile("D:\\新建資料夾\\wulin.txt", "D:\\1061321",1024*1024*20) private static void cutFile(String src, String endsrc, int num) { FileInputStream fis = null; File file = null; try { fis = new FileInputStream(src); file = new File(src);
//建立規定大小的byte陣列 byte[] b = new byte[num]; int len = 0; //name為以後的小檔案命名做準備 int name = 1; //遍歷將大檔案讀入byte陣列中,當byte陣列讀滿後寫入對應的小檔案中 while ((len = fis.read(b)) != -1) { //分別找到原大檔案的檔名和檔案型別,為下面的小檔案命名做準備 String name2 = file.getName();
int lastIndexOf = name2.lastIndexOf("."); String substring = name2.substring(0, lastIndexOf); String substring2 = name2.substring(lastIndexOf, name2.length()); FileOutputStream fos = new FileOutputStream(endsrc + "\\\\"+ substring + "-" + name + substring2); //將byte陣列寫入對應的小檔案中 fos.write(b, 0, len); //結束資源 fos.close(); name++; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fis != null) { //結束資源 fis.close(); } } catch (IOException e) { e.printStackTrace(); } } } }