RandomAccessFile的總結

最近學習了RandomAccessFile,對一些概念進行一個總結。
1,RandomAccessFile打開文件有兩種模式:rw(讀寫)和r(只讀),沒有w(只寫),因爲寫是要建立在讀取的前提下的,沒有讀就不會有寫。
2,RandomAccessFile在調用write()方法時,是按順序將數據寫入文件的,如果在讀取數據時不按照寫入的順序讀取就會讀取出錯誤的數據。
3,write()方法是一次只能寫入一個字節,而writeInt(int v)是一次性按照4個字節寫入。對應write()方法,RandomAccessFile也有響應的read()方法,和write()方法一樣,read()每次也只能從文件中讀取一個字節,並以int值的形式返回,該int值只有低8位有效,若讀取到文件末尾,即EOF,則返回-1。
4,將字符串寫入文件需先將字符串轉換爲字節數組,調用字符串的getBytes(String charsetName)方法將字符串轉換爲字節數組strArr,然後調用RandomAccessFile的write(byte[] b)方法將字節數組寫入文件。通常將字節數組的長度作爲一個int值先於字節數組寫入文件,在讀取時可以根據這個int值來創建相應大小的字節數組
String str = "大家好!!!!!!!!!!!!!!!!!";
byte[] strData = str.getBytes("UTF-8");
raf.writeInt(strData.length);
raf.write(strData);
讀取文件中的字節數組可以調用read(byte[] b)方法,先創建一個字節數組strArr,通過調用read(strArr)方法將字節存入strArr中,再通過String的構造方法String(byte[] b,String charsetName),將字節數組轉換爲字符串
int lenth=raf.readInt();
byte[] strData=new byte[lenth];
raf.read(strData);
String str=new String(strData,"UTF-8");
System.out.println(str);
5,RandomAccessFile的對應基本數據類型的序列化方法有writeInt(int v),writeLong(long v),writeDouble(double v)等。
對應的RandomAccessFile的對應基本數據類型的反序列化方法有readInt(),readLong(),readDouble()等。
6,RandomAccessFile對文件的操作都是基於遊標的,遊標記錄着文件當前寫到或讀到什麼位置了。調用getFilePointer()方法可以獲取遊標當前的位置。調用seek(long pos)方法可以使遊標移動到相應的位置以便我們對文件進行操作。
7,對於字符串的寫入有一簡便方法writeUTF(String str),但只限於UTF-8編碼下的字符串。對於不是UTF-8編碼的字符串就只能按照上面說過的方法來進行操作。
8,使用完必須將RandomAccessFile關閉,即調用close()方法
9,關於文件複製的操作,
import java.io.RandomAccessFile;

/**
 * 複製文件
 * 
 * @author Earl 2014-2-7下午03:26:13
 * 
 */
public class RandomAccessFileDemo06 {
	public static void main(String[] args)throws Exception {
		//用於讀取源文件
		RandomAccessFile src=new RandomAccessFile("JDK.CHM","r");
		
		//用於寫入目標文件
		RandomAccessFile des=new RandomAccessFile("JDKCOPY.CHM","rw");
		long start=System.currentTimeMillis();
		int d=-1;
		while((d=src.read())!=-1){
			des.write(d);
		}
		long end=System.currentTimeMillis();
		System.out.println("複製完畢");
		System.out.println("複製用時:"+(end-start));
	}

}
以上代碼是不使用緩衝數組的方法,該方法複製速度慢,下面使用帶緩衝的方法
import java.io.RandomAccessFile;

/**
 * 基於緩存的複製文件操作
 * 
 * @author Earl 2014-2-7下午04:19:15
 * 
 */
public class RandomAccessFileDemo07 {

	public static void main(String[] args) throws Exception {
		RandomAccessFile src = new RandomAccessFile("JDK.CHM", "r");
		RandomAccessFile des = new RandomAccessFile("JDKCOPY2.CHM", "rw");

		// 創建一個字節數組
		byte[] buffer = new byte[1024 * 10];//並不是緩存區越大速度越快
		// 保存實際讀取到的字節數
		int len = -1;
		long start=System.currentTimeMillis();
		while ((len = src.read(buffer)) > 0) {
			/*
			 * void write(byte[] b,int start,int len):
			 * 將給定的字節數組中從start處開始連續將len個字節寫出
			 */
			des.write(buffer, 0, len);
		}
		long end=System.currentTimeMillis();
		System.out.println("複製完畢");
		System.out.println("用時"+(end-start)+"毫秒");
		src.close();
		des.close();

	}

}



       

發佈了47 篇原創文章 · 獲贊 68 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章