天天看點

java學習筆記:檔案的分割合并

/*  
分割合并小檔案
在c盤先手動粘貼一個jpg檔案,大概2.5M大小,便于觀察
在c盤手動建立一個檔案夾splits,用于存放分割後的檔案
這個圖檔檔案将被分成3塊:(1M ,1M , 0.5M) 大小

本例中有很多細節方面沒寫,隻有大緻的功能實作過程
異常也直接抛了

[示例]:分割合并檔案
*/
import java.io.*;
import java.util.*;

class Demo            
{
  public static void main(String[] args)  throws IOException
  {
    splitFile();//分割
    merger();   //合并檔案

  }
  
  public static void merger() throws IOException //合并檔案
  {
    ArrayList<FileInputStream> al =new ArrayList<FileInputStream>();
    for(int x=1;x<=3;x++)
    {
      al.add(new FileInputStream("c:\\splits\\"+x+".part")); //有3個part檔案要合并
    }
    
    final Iterator<FileInputStream> it = al.iterator();    
    Enumeration<FileInputStream> en =                //實作枚舉器
      new Enumeration<FileInputStream>()              
        {
          public boolean hasMoreElements()
          {
            return it.hasNext(); 
          }
          
          public FileInputStream nextElement() //傳回疊代的下一個枚舉器中的元素
          {
            return it.next(); 
          }
        };
    SequenceInputStream sis = new SequenceInputStream(en); //流串聯器
    FileOutputStream fos = new FileOutputStream("c:\\splits\\all.jpg");
    byte[] buf = new byte[1024*1024]; //1M空間的數組
    int len = 0;
    while(true)
    {
      len = sis.read(buf);
      if(len!=-1)
      {
        fos.write(buf,0,len);
        
      }
      else
      {
        break;
      }
    }
    fos.close();
    sis.close();
        
  }
  
  public static void splitFile() throws IOException  //分割檔案
  {
    FileInputStream fis = new FileInputStream("c:\\m.jpg");
    FileOutputStream fos = null;
    byte[] buf = new byte[1024*1024];
    int len =0;
    int partCount =0; //塊數
    while(true)
    {
      len=fis.read(buf);
      if(len!=-1)
      { 
        partCount++;
        fos = new FileOutputStream("c:\\splits\\"+partCount+".part");
        fos.write(buf,0,len);
        fos.close();
      }
      else
      {
        break;
      }
    }
    fis.close();   
  }
  
}

           
java學習筆記:檔案的分割合并