程式碼分享:檔案的拆分與合併

專案中遇到大檔案上傳,前端會將大檔案切分,後臺進行檔案合併。為實現這個功能,先實現檔案合併功能。

我選擇使用RandomAccessFile,相比FileInputStream。RandomAccessFile多了很多功能,非常方便,具體可檢視API。

拆分檔案程式碼

/** * 拆分檔案 * * @param f */public static void split(File f) throws IOException { // 切分為100K大小的檔案 long fileLength = 1024 * 100; RandomAccessFile src = new RandomAccessFile(f, “r”); int numberOfPieces = (int) (src。length() / fileLength) + 1; int len = -1; byte[] b = new byte[1024]; for (int i = 0; i < numberOfPieces; i++) { String name = “src/test/resources/file/” + f。getName() + “。” + (i + 1); File file = new File(name); file。createNewFile(); RandomAccessFile dest = new RandomAccessFile(file, “rw”); while ((len = src。read(b)) != -1) { dest。write(b, 0, len); //如果太大了就不在這個子檔案寫了 換下一個 if (dest。length() > fileLength) { break; } } dest。close(); } src。close();}效果

程式碼分享:檔案的拆分與合併

可見生成了三個小檔案

檔案合併程式碼

/** * 檔案合併 * @throws IOException */public static void merge() throws IOException { int length = 3; String name = “src/test/resources/file/src。pdf。”; File file = new File(“src/test/resources/file/new。pdf”); file。createNewFile(); RandomAccessFile in = new RandomAccessFile(file, “rw”); in。setLength(0); in。seek(0); byte[] bytes = new byte[1024]; int len = -1; for (int i = 0; i < length; i++) { File src = new File(name + (i + 1)); RandomAccessFile out = new RandomAccessFile(src, “rw”); while ((len = out。read(bytes)) != -1) { in。write(bytes, 0, len); } out。close(); } in。close();}

程式碼分享:檔案的拆分與合併

看一下檔案大小,沒問題

程式碼分享:檔案的拆分與合併

開啟檔案試一下,沒問題,可以正常開啟

百家號原始碼格式沒法看

需要原始碼請關注公-眾-號: 技術筆記與開源分享