檔案分割與合并(Java)

來源:互聯網
上載者:User

標籤:檔案的分割與合并

一、檔案分割

二、檔案合并

方式一:通過檔案追加的方式

方式二:通過SequenceInputStream對其他輸入資料流的邏輯串聯。

測試RandomAccessFile隨機訪問檔案

package FileSplitMerge;import java.io.File;import java.io.IOException;import java.io.RandomAccessFile;import IOOthers.FileUtil;/** * RandomAccessFile * 此類的執行個體支援對隨機訪問檔案的讀取和寫入。 *  * 檔案分割的思路 * 1、 分割的塊數 size   n塊 * 2、 每一塊的大小 blocksize *    最後一塊:總的檔案大小-(n-1)*blockSize */public class Demo01 {    public static void main(String[] args) throws IOException {        RandomAccessFile rnd = new RandomAccessFile(new File("G:/writer.txt"), "r");        //UTF-8-->英文使用1個位元組,中文使用3個位元組來編碼        //GBK-->每個字元佔用2個位元組        //從第12個讀起       這是採用的是UTF-8          rnd.seek(12);        //定義緩衝大小        byte[] flush = new byte[1024];        //接收長度        int len=0;        while(-1!=(len=rnd.read(flush)))        {            if(len>=48)            {                System.out.println(new String(flush,0,48));            }               else {                System.out.println(new String(flush,0,len));            }        }        FileUtil.close(rnd);    }}

運行結果:

都有青春,每個青春都有一個故事?re ESX資源管理與效能最佳化S1.1.11VMware??FT-Practise實驗示範7:vApp-Practise?

檔案的分割與合并

package FileSplitMerge;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.RandomAccessFile;import java.io.SequenceInputStream;import java.util.ArrayList;import java.util.List;import java.util.Vector;import IOOthers.FileUtil;@SuppressWarnings("all")public class SplitFile {    //檔案的路徑    private String filePath;    //塊數    private int size;    //每塊的大小    private long blocksize;    //檔案名稱    private String fileName;    //檔案大小    private long length;    //分割後的存放目錄    private String destBlockPath;    //每塊的名稱    private List<String> blockPath;    public SplitFile() {        blockPath = new ArrayList<String>() ;    }       public SplitFile(String filePath,String destBlockPath) {        this(filePath,1024, destBlockPath);    }    public SplitFile(String filePath, long blocksize,String destBlockPath) {        this();        this.filePath = filePath;        this.destBlockPath = destBlockPath;        this.blocksize = blocksize;    }    /**     * 初始化操作 計算塊數、確定檔案名稱     */    public void init()    {        File src = null;        //健壯性    建立成功就會得到構造方法初始化的值        if(null==filePath || !(src=new File(filePath)).exists())        {            return;        }        if(src.isDirectory())        {            return;        }        //檔案名稱    g:/writer.txt的 writer.txt        this.fileName = src.getName();         //檔案的大小        this.length = src.length();        //修正    每塊的大小        if(this.blocksize>length) //如果每塊的大小大於文本的長度,則每塊的大小=長度        {            this.blocksize = length;        }        //確定塊數        ceil最小(最接近負無窮大)浮點值,該值大於等於該參數,並等於某個整數。        size = (int) Math.ceil(length*1.0/this.blocksize);        //確定檔案的路徑        initPathName();    }    private void initPathName()    {        for(int i=0;i<size;i++)        {            //List容器裡面增加每一塊的路徑            this.blockPath.add(destBlockPath+"/"+this.fileName+".part"+i);        }    }    /**     * 檔案分割     * 確定在第幾塊     * 1、起始位置     * 2、實際大小     * @param destPath 分割檔案存放目錄     * @throws IOException      */    public void split(String destPath) throws IOException    {        //確定檔案的路徑        //每一塊的名稱        //initPathName(destPath);        long beginPos = 0;//起始點        long actualBlockSize = blocksize;//實際大小        //計算所有快的大小、位置、索引        for(int i=0;i<size; i++)        {            if(i == size-1)            {                //最後一塊                actualBlockSize = this.length-beginPos;            }            //具體分割方法     第幾塊    起始分割地址        實際的塊大小            splitDetail(i,beginPos,actualBlockSize);            beginPos += actualBlockSize;//本次的終點,下一次的起點        }    }    /**     * 檔案分割  輸入 輸出     * 檔案拷貝     * @param idx 第幾塊     * @param beginPos 起始點     * @param actualBlockSize 實際大小     * @throws IOException      */    public void splitDetail(int idx,long beginPos,long actualBlockSize) throws IOException    {        //1、建立源        File src = new File(this.filePath);//源檔案        //得到第幾塊的路徑       List容器取出塊路徑        File dest = new File(this.blockPath.get(idx));//目標檔案        //2、選擇流        RandomAccessFile raf = null;//輸入資料流        BufferedOutputStream bos = null;//輸出資料流        try         {             raf = new RandomAccessFile(src, "r");             bos = new BufferedOutputStream(new FileOutputStream(dest));             //3、讀取檔案             raf.seek(beginPos);             //4、緩衝區             byte[] flush = new byte[1024];             int len = 0;             while(-1!=(len=raf.read(flush)))             {                 //寫出                 if(actualBlockSize-len>=0)//判斷是否足夠                 {                     bos.write(flush,0,len);//寫出                     actualBlockSize -= len;//剩餘量                                 }                 else                    {                     //讀取每一塊實際大小的最後一小部分   最後一次寫出                     bos.write(flush,0,(int)actualBlockSize);                     break;//每個block最後一部分讀取完之後,一定要break,否則就會繼續讀取                 }            }        } catch (FileNotFoundException e) {            e.printStackTrace();        }        finally{            FileUtil.close(bos,raf);        }    }    /**     * 檔案的合并   (方法一)     */    public void merge1(String destPath)    {        //建立源        File dest = new File(destPath);        //選擇流        BufferedOutputStream bos = null;//輸出資料流        BufferedInputStream bis = null;//輸入資料流        try {            bos = new BufferedOutputStream(new FileOutputStream(dest,true));//表示追加            for(int i=0; i<this.blockPath.size();i++)            {                //讀取                bis = new BufferedInputStream(new FileInputStream                        (new File(this.blockPath.get(i))));                //緩衝區                byte[] flush = new byte[1024];                //接收長度                int len = 0;                while(-1 !=(len = bis.read(flush)))                {                    //列印到控制台                    //System.out.println(new String(flush,0,len));                    bos.write(flush,0,len);                                 }                bos.flush();                FileUtil.close(bis);            }        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        finally        {            FileUtil.close(bos);        }       }    /**     * 檔案的合并  (方法二)     */     public void merge(String destPath) throws IOException    {        //1、建立源        File dest = new File(destPath);        //2、選擇流        //SequenceInputStream 表示其他輸入資料流的邏輯串聯。它從輸入資料流的有序集合開始,        //並從第一個輸入資料流開始讀取,直到到達檔案末尾,接著從第二個輸入資料流讀取,依次類推,        //直到到達包含的最後一個輸入資料流的檔案末尾為止。         SequenceInputStream sis = null;//輸入資料流        BufferedOutputStream bos = null;//輸出源           //建立一個容器        Vector<InputStream> vi = new Vector<InputStream>();        for(int i=0; i<this.blockPath.size();i++)        {            vi.add(new BufferedInputStream(                    new FileInputStream(new File(this.blockPath.get(i)))));             }        //SequenceInputStream sis = new SequenceInputStream(vi.elements());         bos = new BufferedOutputStream(new FileOutputStream(dest,true));//表示追加        sis = new SequenceInputStream(vi.elements());        //緩衝區        byte[] flush = new byte[1024];        //接收長度        int len = 0;        while(-1 !=(len = sis.read(flush)))        {            //列印到控制台            //System.out.println(new String(flush,0,len));            bos.write(flush,0,len);             }        bos.flush();        FileUtil.close(sis);    }    public static void main(String[] args) {        //源檔案路徑、每塊的大小(位元組數)、目標快的路徑        SplitFile split = new SplitFile("g:/writer.txt",100,"g:/try");        //檔案初始化        split.init();        //檔案分割        try {            //split.split("g:/try");            split.split(split.destBlockPath);           } catch (IOException e) {            e.printStackTrace();        }        //檔案合并        try {            split.merge("g:/try/test.txt");        } catch (IOException e) {            e.printStackTrace();        }        //System.out.println(file.size);    }}

檔案分割與合并(Java)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.