1. 程式人生 > >JavaIo——運用RandomAccessFile實現檔案的多執行緒下載

JavaIo——運用RandomAccessFile實現檔案的多執行緒下載

文章轉載自:http://blog.csdn.net/akon_vm/article/details/7429245

利用RandomAccessFile實現檔案的多執行緒下載,即多執行緒下載一個檔案時,將檔案分成幾塊,每塊用不同的執行緒進行下載。下面是一個利用多執行緒在寫檔案時的例子,其中預先分配檔案所需要的空間,然後在所分配的空間中進行分塊,然後寫入:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 測試利用多執行緒進行檔案的寫操作
 */
public class Test {

	public static void main(String[] args) throws Exception {
		// 預分配檔案所佔的磁碟空間,磁碟中會建立一個指定大小的檔案
		RandomAccessFile raf = new RandomAccessFile("D://abc.txt", "rw");
		raf.setLength(1024*1024); // 預分配 1M 的檔案空間
		raf.close();
		
		// 所要寫入的檔案內容
		String s1 = "第一個字串";
		String s2 = "第二個字串";
		String s3 = "第三個字串";
		String s4 = "第四個字串";
		String s5 = "第五個字串";
		
		// 利用多執行緒同時寫入一個檔案
		new FileWriteThread(1024*1,s1.getBytes()).start(); // 從檔案的1024位元組之後開始寫入資料
		new FileWriteThread(1024*2,s2.getBytes()).start(); // 從檔案的2048位元組之後開始寫入資料
		new FileWriteThread(1024*3,s3.getBytes()).start(); // 從檔案的3072位元組之後開始寫入資料
		new FileWriteThread(1024*4,s4.getBytes()).start(); // 從檔案的4096位元組之後開始寫入資料
		new FileWriteThread(1024*5,s5.getBytes()).start(); // 從檔案的5120位元組之後開始寫入資料
	}
	
	// 利用執行緒在檔案的指定位置寫入指定資料
	static class FileWriteThread extends Thread{
		private int skip;
		private byte[] content;
		
		public FileWriteThread(int skip,byte[] content){
			this.skip = skip;
			this.content = content;
		}
		
		public void run(){
			RandomAccessFile raf = null;
			try {
				raf = new RandomAccessFile("D://abc.txt", "rw");
				raf.seek(skip);
				raf.write(content);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					raf.close();
				} catch (Exception e) {
				}
			}
		}
	}

}