最近在學習大數據相關的知識點,其中需要實現文件的切片和合並,完整的java實現代碼,以下貼出個人代碼,僅供參考
首先建一個SplitUtil工具類,在工具類中有三個方法getSplitFile,getWrite,merge
1,文件拆分代碼
public static void getSplitFile(String file,int count){ //預分配文件所占用的磁盤空間,在磁盤創建一個指定大小的文件,“r”表示只讀,“rw”支持隨機讀寫 try { RandomAccessFile raf = new RandomAccessFile(new File(file), "r"); //計算文件大小 long length = raf.length(); System.out.println(length); //計算文件切片后每一份文件的大小 long maxSize = length / count; System.out.println(maxSize); long offset = 0L;//定義初始文件的偏移量(讀取進度) //開始切割文件 for(int i = 0; i < count - 1; i++){ //count-1最后一份文件不處理 //標記初始化 long fbegin = offset; //分割第幾份文件 long fend = (i+1) * maxSize; //寫入文件 offset = getWrite(file, i, fbegin, fend); } //剩余部分文件寫入到最后一份(如果不能平平均分配的時候) if (length - offset > 0) { //寫入文件 getWrite(file, count-1, offset, length); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
2,getWrite文件寫入代碼
/** * 指定文件每一份的邊界,寫入不同文件中 * @param file 源文件 * @param index 源文件的順序標識 * @param begin開始指針的位置 * @param end 結束指針的位置 * @return long */ public static long getWrite(String file,int index,long begin,long end){ long endPointer = 0L; try { //申明文件切割后的文件磁盤 RandomAccessFile in = new RandomAccessFile(new File(file), "r"); //定義一個可讀,可寫的文件並且后綴名為.tmp的二進制文件 RandomAccessFile out = new RandomAccessFile(new File(file + "_" + index + ".tmp"), "rw"); //申明具體每一文件的字節數組 byte[] b = new byte[1024]; int n = 0; //從指定位置讀取文件字節流 in.seek(begin); //判斷文件流讀取的邊界 while(in.getFilePointer() <= end && (n = in.read(b)) != -1){ //從指定每一份文件的范圍,寫入不同的文件 out.write(b, 0, n); } //定義當前讀取文件的指針 endPointer = in.getFilePointer(); //關閉輸入流 in.close(); //關閉輸出流 out.close(); } catch (Exception e) { e.printStackTrace(); } return endPointer; }
3.文件合並代碼
/** * 文件合並 * @param file 指定合並文件 * @param tempFile 分割前的文件名 * @param tempCount 文件個數 */ public static void merge(String file,String tempFile,int tempCount){ RandomAccessFile raf = null; try { //申明隨機讀取文件RandomAccessFile raf = new RandomAccessFile(new File(file), "rw"); //開始合並文件,對應切片的二進制文件 for (int i = 0; i < tempCount; i++) { //讀取切片文件 RandomAccessFile reader = new RandomAccessFile(new File(tempFile + "_" + i + ".tmp"), "r"); byte[] b = new byte[1024]; int n = 0; while((n = reader.read(b)) != -1){ raf.write(b, 0, n);//一邊讀,一邊寫 } } } catch (Exception e) { e.printStackTrace(); }finally{ try { raf.close(); } catch (IOException e) { e.printStackTrace(); } }
最后在主程序里面調用就可以了
public static void main(String[] args) { String file = "F:\\java-study\\img\\mv.jpg"; int count = 5; //1.根據現有的文件編寫文件編寫文件切片工具類 //2.寫入到二進制臨時文件 // getSplitFile(file, count); //3.根據實際的需求合並指定數量的文件 String tempFile = "F:\\java-study\\img\\img.jpg"; merge(file, tempFile, 5); }
以上代碼可實現圖片,文檔,mp3,mp4等文件的拆分與合並,下面是圖片切片和拆分的效果圖