檔案的隨機訪問主要是通過RandomAccessFile來完成,它使用seek()方法從檔案中的一個記錄移動到下一個記錄進行讀或者寫,而不需要知道總共多少個記錄。它不需要把所有的記錄全部裝進記憶體再進行讀寫,對於訪問大檔案來說,這是一種高效的選擇。
建構函式:兩種方法來制定對應的檔案:字串路徑和File
| 構造方法摘要 |
RandomAccessFile(File file, String mode)
建立從中讀取和向其中寫入(可選)的隨機訪問檔案流,該檔案由 File 參數指定。 |
RandomAccessFile(String name, String mode)
建立從中讀取和向其中寫入(可選)的隨機訪問檔案流,該檔案具有指定名稱。 |
常用方法:
| 方法摘要 |
void |
close()
關閉此隨機訪問檔案流並釋放與該流關聯的所有系統資源。 |
FileChannel |
getChannel()
返回與此檔案關聯的唯一 FileChannel 對象。 |
FileDescriptor |
getFD()
返回與此流關聯的不透明檔案描述符對象。 |
long |
getFilePointer()
返回此檔案中的當前位移量。 |
long |
length()
返回此檔案的長度。 |
int |
read()
從此檔案中讀取一個資料位元組。 |
int |
read(byte[] b)
將最多 b.length 個資料位元組從此檔案讀入 byte 數組。 |
int |
read(byte[] b, int off, int len)
將最多 len 個資料位元組從此檔案讀入 byte 數組。 |
boolean |
readBoolean()
從此檔案讀取一個 boolean。 |
byte |
readByte()
從此檔案讀取一個有符號的八位值。 |
char |
readChar()
從此檔案讀取一個字元。 |
double |
readDouble()
從此檔案讀取一個 double。 |
float |
readFloat()
從此檔案讀取一個 float。 |
void |
readFully(byte[] b)
將 b.length 個位元組從此檔案讀入 byte 數組,並從當前檔案指標開始。 |
void |
readFully(byte[] b, int off, int len)
將正好 len 個位元組從此檔案讀入 byte 數組,並從當前檔案指標開始。 |
int |
readInt()
從此檔案讀取一個有符號的 32 位整數。 |
String |
readLine()
從此檔案讀取文本的下一行。 |
long |
readLong()
從此檔案讀取一個有符號的 64 位元整數。 |
short |
readShort()
從此檔案讀取一個有符號的 16 位元。 |
int |
readUnsignedByte()
從此檔案讀取一個無符號的八位元。 |
int |
readUnsignedShort()
從此檔案讀取一個無符號的 16 位元。 |
String |
readUTF()
從此檔案讀取一個字串。 |
void |
seek(long pos)
設定到此檔案開頭測量到的檔案指標位移量,在該位置發生下一個讀取或寫入操作。 |
void |
setLength(long newLength)
設定此檔案的長度。 |
int |
skipBytes(int n)
嘗試跳過輸入的 n 個位元組以丟棄跳過的位元組。 |
void |
write(byte[] b)
將 b.length 個位元組從指定 byte 數組寫入到此檔案,並從當前檔案指標開始。 |
void |
write(byte[] b, int off, int len)
將 len 個位元組從指定 byte 數組寫入到此檔案,並從位移量 off 處開始。 |
void |
write(int b)
向此檔案寫入指定的位元組。 |
void |
writeBoolean(boolean v)
按單位元組值將 boolean 寫入該檔案。 |
void |
writeByte(int v)
按單位元組值將 byte 寫入該檔案。 |
void |
writeBytes(String s)
按位元組序列將該字串寫入該檔案。 |
void |
writeChar(int v)
按雙位元組值將 char 寫入該檔案,先寫高位元組。 |
void |
writeChars(String s)
按字元序列將一個字串寫入該檔案。 |
void |
writeDouble(double v)
使用 Double 類中的 doubleToLongBits 方法將雙精確度參數轉換為一個 long,然後按八位元組數量將該 long 值寫入該檔案,先定高位元組。 |
void |
writeFloat(float v)
使用 Float 類中的 floatToIntBits 方法將浮點參數轉換為一個 int,然後按四位元組數量將該 int 值寫入該檔案,先寫高位元組。 |
void |
writeInt(int v)
按四個位元組將 int 寫入該檔案,先寫高位元組。 |
void |
writeLong(long v)
按八個位元組將 long 寫入該檔案,先寫高位元組。 |
void |
writeShort(int v)
按兩個位元組將 short 寫入該檔案,先寫高位元組。 |
void |
writeUTF(String str)
使用 modified UTF-8 編碼以與機器無關的方式將一個字串寫入該檔案。 |
測試程式:將4條person資料按照一定的格式(各欄位定長寫入到檔案),然後隨機遍曆整個檔案,輸出所有的記錄。然後找到包含關鍵字的的記錄。
package FileOperation;import java.io.IOException;import java.io.RandomAccessFile;import java.util.ArrayList;import java.util.List;public class FileRandomAccess {/** 姓名在檔案中的長度 */public static final int NAME_LENGTH = 100;/** 年齡在檔案中的長度 */public static final int INT_LENGTH = 8;public static final int DESCRIPTION_LENGTH = 200;/** 每條 Person 記錄在檔案中的長度 */public static final int PERSON_LENGTH = NAME_LENGTH + INT_LENGTH + DESCRIPTION_LENGTH;//Person內部類static class Person{public String name;public int age;public String description;public Person(String name, int age, String description){this.name = name;this.age = age;this.description = description;}public String toString(){return "Person[name=\"" + name + "\", age=\"" + age + "\", description=\"" + description + "\"]";}}//定義一個Person類型的數組static Person[] person = new Person[] { new Person("杜甫", 45, "唐朝現實主義詩人"),new Person("愛因斯坦", 20, "偉大的物理學家,提出相對論理論。"), new Person("李白", 20, "唐朝浪漫主義詩人"), new Person("曹雪芹", 47, "《紅樓夢》作者"), };//main函數public static void main(String[] args) throws IOException{//構造一個隨機訪問類的file對象RandomAccessFile file = new RandomAccessFile("C:\\person.dat", "rw");// 初始化資料 根據初始化資料設定檔案長度file.setLength(person.length * PERSON_LENGTH);for(int i=0; i<person.length; i++){writePerson(file, person[i]);//調用writePerson}System.out.println("\r\n列出檔案中所有的資料:");Person[] allPersons = listAllPerson(file);//調用listAllPerson返回一個person數組for(int i=0; i<allPersons.length; i++){System.out.println(allPersons[i]);}System.out.println("\r\n在檔案中尋找關鍵字 雪,結果如下:");Person p = findPerson(file, "雪");//調用findPerson尋找file裡的keywordSystem.out.println("找到結果:" + p);file.close();}// 寫 String 類型資料,要注意寫String和寫int的區別,public static void writeString(RandomAccessFile file, String name, int fieldLength) throws IOException{file.writeUTF(name);int length = name.getBytes("UTF-8").length;file.skipBytes(fieldLength - length);//跳過沒有用完的位元組,保持對齊}// 寫 int 類型資料public static void writeInt(RandomAccessFile file, int age) throws IOException{file.writeInt(age);}//寫person對象(寫 String,寫 int )public static void writePerson(RandomAccessFile file, Person person) throws IOException{writeString(file, person.name, NAME_LENGTH);writeInt(file, person.age);writeString(file, person.description, DESCRIPTION_LENGTH);}// 讀 String 類型資料public static String readString(RandomAccessFile file, int fieldLength) throws IOException{String name = file.readUTF();int length = name.getBytes("UTF-8").length;file.skipBytes(fieldLength - length);return name;}// 讀 int 類型資料public static int readInt(RandomAccessFile file) throws IOException{return file.readInt();}//讀person對象(讀 String,讀 int)public static Person readPerson(RandomAccessFile file) throws IOException {// 找到檔案頭了if(file.getFilePointer() >= file.length()){return null;}return new Person(readString(file, NAME_LENGTH), // namereadInt(file), // agereadString(file, DESCRIPTION_LENGTH)// description);}// 列出資料檔案中的所有的資料public static Person[] listAllPerson(RandomAccessFile file) throws IOException {List list = new ArrayList();file.seek(0);while(true){Person person = readPerson(file);if(person == null)break;list.add(person);}Person[] person = new Person[list.size()];list.toArray(person);return person;}// 尋找合格資料public static Person findPerson(RandomAccessFile file, String keyword) throws IOException {// 從開始尋找記錄file.seek(0);while(true){Person person = readPerson(file);//每次讀一個person,注意每次seek都要往後移動if(person == null)break;if(person.name.contains(keyword)){return person;}}return null;}}
運行結果:
列出檔案中所有的資料:
Person[name="杜甫", age="45", description="唐朝現實主義詩人"]
Person[name="愛因斯坦", age="20", description="偉大的物理學家,提出相對論理論。"]
Person[name="李白", age="20", description="唐朝浪漫主義詩人"]
Person[name="曹雪芹", age="47", description="《紅樓夢》作者"]
在檔案中尋找關鍵字 雪,結果如下:
找到結果:Person[name="曹雪芹", age="47", description="《紅樓夢》作者"]