1. 程式人生 > >Java IO流 --- 隨機流2

Java IO流 --- 隨機流2

本文轉自

本文主要介紹隨機流的斷點續傳的具體使用

斷點續傳原理

首先把隨機訪問的檔案物件看作儲存在檔案系統中的一個大型 byte 陣列,然後通過指向該 byte 陣列的游標或索引(即:檔案指標 FilePointer)在該陣列任意位置讀取或寫入任意資料

相關方法說明

1 物件宣告

RandomAccessFile raf = new RandomAccessFile(File file, String mode); 其中 mode 的值可選 r w rw

2 獲取當前檔案的位置

int RandomAccessFile.getFilePointer();

3 改變檔案指標位置(相對位置,絕對位置)

1 絕對位置:RandomAccessFile.seek(int index); 2 相對位置:RandomAccessFile.skipByte(int step); // 相對當前位置

4 給寫入檔案預留空間

RandomAccessFile.setLength(long len);

使用多執行緒複製大檔案

1 自定義執行緒,實現對檔案的隨機讀寫

public class MyThread extends Thread{
	
	private RandomAccessFile rafR; // 讀取檔案隨機流
	private RandomAccessFile rafW; // 寫入檔案隨機流
private long startPoint; public MyThread(File fR,File fW,long startPoint){ try { this.rafR = new RandomAccessFile(fR,"r"); this.rafW = new RandomAccessFile(fW,"rw"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.startPoint =
startPoint; } public void run(){ try { rafR.seek(startPoint); rafW.seek(startPoint); byte[] by = new byte[1024]; int len = 0; int maxSize = 0; while( (len= rafR.read(by)) !=-1 && maxSize< RACTest.copySize ){ rafW.write(by,0,len); maxSize++; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { rafR.close(); rafW.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }

2 將大檔案劃分為小模組,建立多個子執行緒執行檔案複製

public class RACTest {
	
	final static int copySize = 100;

	
	public static void main(String[] args) throws IOException, InterruptedException {
		
		File f1 = new File("E:"+File.separator+"IO流.txt"); // 讀入檔案路徑
		File f2 = new File("E:"+File.separator+"IO流1.txt"); // 寫出檔案路徑
		
		if(!f1.exists()){
			System.out.println("讀入檔案不存在");
			return;
		}
		
		RandomAccessFile rafR = new RandomAccessFile(f1,"r"); // 讀入隨機流
		RandomAccessFile rafW = new RandomAccessFile(f2,"rw"); // 寫出隨機流
		
		long length = rafR.length();  // 讀取檔案的大學
		rafW.setLength(length);       // 設定目的檔案大小
		
		int bord = (int) length/ copySize;
		bord = (int) length % copySize == 0? bord: bord+1;
		
		for(int i=1;i<bord;i++)
			new MyThread(f1,f2,i*copySize*1024).start();
		
		rafR.seek(0);
		rafW.seek(0);
		byte[] by = new byte[1024];
		int len = 0;
		int maxSize = 0;
		while((len = rafR.read(by))!=-1 && maxSize<copySize){
			rafW.write(by,0,len);
			maxSize++;	
		}
		
		rafR.close();
		rafW.close();
		
		Thread.sleep(3000); // 延時 3秒,保證所有執行緒執行完畢
		System.out.println("複製完成");
	}

}