RandomAceessFile類
RandomAccessFile類是一個專門讀寫文件的類,封裝了基本的IO流,在讀寫文件內容方面比常規IO流更方便、更靈活。但也僅限於讀寫文件,無法像IO流一樣,可以傳輸內存和網絡中的數據。
RandomAccessFile常用方法和使用方式
- getFilePointer() :獲取當前文件的記錄指針位置
- seek(long pos):把記錄指針移到pos處
- read()和write():讀取內容和寫入內容
- readXxx()和writeXxx():用於處理各種值類型
- writeBytes()和writeChars()可以寫入字符串,編碼不一致會造成亂碼。所以推薦String.getBytes(),用write()來寫入。
總體來說,如果只處理文件的話,使用RandomAccessFile很方便,而且讀寫方法和IO流都差不多,只是針對不同類型數據進行擴展,使用簡單明了。最重要的就是該類的seek()方法,該方法可以指定讀寫的位置。還有該類構造器需要一個參數來確定使用什么模式。
r:只讀模式
rw:讀寫模式
rwd:和rw差不多,但需要對文件內容每個更新都進行同步。
代碼示例:
(一)RandomAccessFile讀取文件內容
//rw : 設置模式為讀寫模式 RandomAccessFile raf = new RandomAccessFile("D:\\reviewIO\\runtime.txt","rw"); System.out.println("當前記錄指針位置:" + raf.getFilePointer()); byte[] buf = new byte[1024]; int len = 0; while((len = raf.read(buf)) != -1) { System.out.println(new String(buf)); }
(二)RandomAccessFile寫入數據到文件中
public class Test { public static void main(String[] args) throws IOException { //要讀寫的數據源 File f = new File("D:\\reviewIO\\RandomAccessFileTest.txt"); //鍵盤輸入作為數據來源 Scanner sc = new Scanner(System.in); //指定文件不存在就創建同名文件 if(!f.exists()) f.createNewFile(); //rw : 設為讀寫模式 RandomAccessFile raf = new RandomAccessFile(f,"rw"); System.out.println("當前記錄指針位置:" + raf.getFilePointer()); while(true) { String str = sc.next(); raf.writeBytes(str); System.out.println("當前記錄指針位置:" + raf.getFilePointer()); //輸入end結束循環 if(str.equals("end")) break; } } }
- 使用小結:RandomAccessFile寫入數據到文件中不會覆蓋文件內容。只要程序每運行一次,該類的記錄指針總是為0,這意味着從文件最前端開始讀寫,所以需要注意。
(三)RandomAccessFile的記錄指針放在文件尾部,用於添加內容
public class Test { public static void main(String[] args) throws IOException { //讀寫的數據源 File f = new File("D:\\reviewIO\\RAF.txt"); //指定文件不存在就創建同名文件 if(!f.exists()) f.createNewFile(); //rw : 設為讀寫模式 RandomAccessFile raf = new RandomAccessFile(f,"rw"); System.out.println("當前記錄指針位置:" + raf.getFilePointer()); //記錄指針與文件內容長度相等 raf.seek(raf.length()); System.out.println("當前文件長度:" + raf.length()); //以字節形式寫入字符串 raf.write("ABCDEFG寫入尾部".getBytes()); System.out.println("當前記錄指針位置:" + raf.getFilePointer()); } }
- 使用小結:如果使用RandomAccessFile添加內容,要把記錄指針設為同文件一樣的長度,保證在文件的尾部進行寫入數據。write()寫入中文,使用String.getByte(),保證兩者編碼一致。