本文實例講述了Java實現大文件的切割與合并操作。分享給大家供大家參考,具體如下:
這里實現對大文件的切割與合并。
按指定個數切(如把一個文件切成10份)或按指定大小切(如每份最大不超過10M),這兩種方式都可以。
在這里我只是給大家寫下我自己的一點簡單的代碼:
package io2;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.SequenceInputStream;import java.util.ArrayList;import java.util.Collections;import java.util.Enumeration;import javax.swing.JFileChooser;public class FileSplitDemo {/*** 實現對大文件的切割與合并。 按指定個數切(如把一個文件切成10份)或按指定大小切(如每份最大不超過10M),這兩種方式都可以。*/public static void main(String[] args) {JFileChooser jfc = new JFileChooser();// Swing中的選擇文件// 選擇文件int result = jfc.showOpenDialog(null);// 顯示框架用于選擇文件File file = null;// 要切割的文件File dest = null;// 目的地文件try {if (result == JFileChooser.APPROVE_OPTION) {// 選中文件// 切割文件file = jfc.getSelectedFile();// 用戶選擇的文件dest = new File(file.getParent(), "spliFile");cutingFile(file, dest);// 切割方法// 2合并(運行時,直接對剛才切割的那些文件碎片進行合并)String fileName = file.getName();mergeDemo(dest, fileName);// 合并文件}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}private static void mergeDemo(File dest, String fileName)throws IOException {// 健壯性防護(用File對象去開道)if (!dest.exists()) {throw new RuntimeException("文件不存在");}// 用一個文件數組將里面的文件都裝起來File parth[] = dest.listFiles();// 返回一個抽象路徑名數組,這些路徑名表示此抽象路徑名表示的目錄中的文件。if (parth.length == 0) {throw new RuntimeException("碎片不存在");}// y用序列流來合并ArrayList<FileInputStream> list = new ArrayList<FileInputStream>();// for (int i = 0; i < parth.length; i++) {// list.add(new FileInputStream(parth[i]));//不能這樣,這樣合并出來的文件是順序亂的// }for (int i = 0; i < parth.length; i++) {list.add(new FileInputStream(new File(dest, fileName + (i + 1)+ "part")));// 套接技術,文件加的順序要和原文件一樣}// 枚舉對象接口Enumeration<FileInputStream> en = Collections.enumeration(list);SequenceInputStream sq = new SequenceInputStream(en);// 寫入到新文件中FileOutputStream fou = new FileOutputStream(new File(dest, fileName));byte buf[] = new byte[1024];sq.read(buf);int len = 0;while ((len = sq.read(buf)) > 0) {fou.write(buf, 0, len);}fou.close();sq.close();}private static void cutingFile(File source, File dest) {// 切割try {FileInputStream fis = new FileInputStream(source);if (!dest.exists()) {// 文件操作IO流要判斷文件是否存在。dest.mkdir();}byte buf[] = new byte[1024 * 1024];// 1Mfis.read(buf);int len = 0;int cout = 1;while ((len = fis.read(buf)) != -1) {// 用OUT流來切割文件FileOutputStream fout = new FileOutputStream(new File(dest,source.getName() + (cout++) + "part"));fout.write(buf, 0, len);fout.close();}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
文件切割:把一個文件切割成多個碎片,每個碎片的大小不超過1M。自己可把功能進一步擴展:切割前的文件名、長度,切割后的碎片個數、文件名等信息可寫到第一個碎片中或另外用properties把這些寫到配置文件中。
文件合并:這里簡單假設已知被合并目錄的File對象和原文件的名字。其實這些完全可以做成活的,如把這些信息保存在碎片文件或配置文件,也可以同樣用文件選擇對話框來讀取用戶的選擇。
希望本文所述對大家java程序設計有所幫助。
新聞熱點
疑難解答
圖片精選