天天看點

IO流檔案"切割者"

檔案切割者RandomAccessFile

public class TestIOS{
	public static void main(String [] args){
		// src需要切割的檔案路徑
	 	String src="src/com/sxt/test/TestIOS.java";
		RandTest1(src);
	 }
   /**
     * 檔案分割
     */
    public static void RandTest1(String src){
        //擷取資料源
        File file=new File(src);
        //擷取檔案的總長度
        long len = file.length();
        System.out.println(len);

        //擷取檔案一次性讀取的大小
        int size=2048;
        //檔案的總塊數            四舍五入取整
        int kuaishu = (int) Math.ceil((len*1.0)/size);
        System.out.println(kuaishu);

        //初始長度
        int start=0;
        //實際長度=固定長度>總長度?說明檔案已經讀到最後一塊(讀取剩餘長度):檔案沒有讀到最後一塊(讀取固定長度)
        int actualSize= size>len? (int) len :size;
        
		//通過塊數進行周遊
        for(int i=0;i<kuaishu;i++){
            //不斷地更新初始長度
            start=i*size;
            //如果固定塊數為最後一塊   實際長度就等于剩餘長度值        
            if (i==kuaishu-1){
                actualSize= (int) len;
            }else{
                //否則的話就是   沒有到最後一塊      實際長度等于固定長度
                actualSize=size;
                //将已經用過的長度值減掉
                len-=actualSize;
            }
            
            //調用讀取檔案的方法
            RandTest(i,start,actualSize,src);
            
            System.out.println();
            System.out.println();
            System.out.println("塊數:"+i+"---------初始值:"+start+"-----------實際大小:"+actualSize);
            System.out.println();
            System.out.println();
        }
    }

    /**
     * 形參意思如下:
     * 第幾塊      起始位置        實際大小		檔案路徑
     * 分段截取指定的資料,檔案分割
     */
    public  static void RandTest(int i,int startPro,int actualSize,String src){
        //檔案分割
        RandomAccessFile raf=null;
        try {
            raf = new RandomAccessFile(src,"r");

            //***從起始位置索引處開始進行擷取資料
            raf.seek(startPro);
            //建立位元組數組做為緩沖區
            byte[] flash = new byte[2048];
            //聲明一個整形變量,用來擷取檔案讀取的長度
            int len=-1;
     		//循環讀取檔案	直到檔案讀取結束.len=-1;
            while ((len=raf.read(flash))!=-1){
           		 //如果本次讀取的内容長度>=上次讀取的長度	則繼續讀
                if (actualSize>=len){      
                    System.out.println(new String(flash,0,len));
                    actualSize-=len;        //下次實際要讀的容量=固定容量-已讀容量
                }else{
                    System.out.println(new String(flash,0,actualSize));//讀取剩餘的資料,之後跳出循環
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
 
}