標籤:java accessfile io操作 檔案操作
簡介:
RandomAccessFile類可以對檔案隨機訪問的操作,訪問包括讀和寫操作。該類的讀寫是基於指標的操作。
RandomAccessFile對檔案進行隨機訪問操作時有兩個模式,一種是唯讀(r),另一種是讀寫(rw),需在建立RandomAccessFile對象時傳入一個參數進行設定,第一個參數代表要訪問的檔案,第二個參數代表設定訪問模式
RandomAccessFile(File file,String mode)
RandomAccessFile(String filename,String mode)
唯讀模式: new RandomAccessFile(“filename”,”r”);
讀寫入模式: new RandomAccessFile(filename,”rw”);
public static void main(String[] args) throws IOException { //以讀寫方式開啟並寫入一行文本 File fis = new File("test.date"); RandomAccessFile raf = new RandomAccessFile(fis, "rw"); byte[] writeStr = "this is a demo!".getBytes(); raf.write(writeStr); raf.close(); //以唯讀方式開啟並讀取一行資料 RandomAccessFile rafRead = new RandomAccessFile("test.date", "r"); System.out.println(rafRead.readLine()); rafRead.close(); }
運行結果:
this is a demo!
RandomAccessFile常用方法匯總:
void write(int d)
該方法會根據當前指標所在位置處寫入一個位元組,是將參數int的”低8位”寫出
int read()
如果返回-1表示讀取到了檔案末尾EOF(EOF:End Of File)! 每次讀取後自動移動檔案指標, 準備下次讀取。
void write(byte[] d)
根據當前指標所在位置處連續寫出給定數組中的所有位元組
void write(byte[] d,int offset,int len)
根據當前指標所在位置處連續寫出給定數組中的部分位元組,這個部分是從數組的offset處開始,連續len個位元組
int read(byte[] b)
從檔案中嘗試最多讀取給定數組的總長度的位元組量,並從給定的位元組數組第一個位置開始,將讀取到的位元組順序存放至數組中,傳回值為實際讀取到的位元組量
void close()
RandomAccessFile在對檔案訪問的操作全部結束後,要調用close()方法來釋放與其關聯的所有系統資源
public static void main(String[] args) throws IOException { //以讀寫方式開啟並寫入一行文本 File fis = new File("test.dat"); RandomAccessFile rafw = new RandomAccessFile(fis, "rw"); byte[] writeStr = "this is a demo!\n".getBytes(); for(int i = 0; i < 10; i++) { rafw.write(writeStr, 0, writeStr.length); } rafw.close(); //以唯讀方式開啟test.dat RandomAccessFile rafr = new RandomAccessFile(fis, "r"); byte[] rd = new byte[1024]; int len = -1; //迴圈讀取,讀到結束後len被重新賦值為-1 while((len = rafr.read(rd))!= -1) { System.out.println(new String(rd)); } System.out.println("讀取結束,len="+len); rafr.close(); }
運行結果:
this is a demo!
this is a demo!
this is a demo!
this is a demo!
this is a demo!
this is a demo!
this is a demo!
this is a demo!
this is a demo!
this is a demo!
讀取結束,len=-1
檔案指標操作:
RandomAccessFile的讀寫操作都是基於指標的,也就是說總是在指標當前所指向的位置進行讀寫操作。
long getFilePointer()
擷取當前指標位置
void seek(long pos)
使用該方法可以移動指標到指定位置。
int skipBytes(int n)
嘗試跳過輸入的 n 個位元組以丟棄跳過的位元組
實現檔案追加:
public static void main(String[] args) throws IOException { RandomAccessFile raf = new RandomAccessFile("test.dat", "rw"); //將記錄指標移動到檔案最後 ,進行追加操作 raf.seek(raf.length()); raf.write("追加後的文本\n".getBytes()); raf.close(); }
運行後test.dat常值內容:
this is a demo!
this is a demo!
this is a demo!
this is a demo!
this is a demo!
this is a demo!
this is a demo!
this is a demo!
this is a demo!
this is a demo!
追加後的文本
總結:
RandomAccessFile,優點是可以控制指標的位置,對檔案進行指定位置的讀寫操作。
但是同時也有一些缺點,執行效率比較慢,大量進行指標控制操作很耗記憶體。
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Java RandomAccessFile檔案操作詳解