Java技術篇·IO包·RandomAccessFile類
阿新 • • 發佈:2018-12-22
有關知識及說明,全部在下邊程式中體現。
package com.io; import java.io.File; import java.io.RandomAccessFile; /** * RandomAccessFile Java提供的對檔案內容的訪問,既可以讀也可以寫。 * 支援隨機訪問,可以訪問任意位置。 * java檔案模型:在硬碟上是byte byte byte儲存的,是資料的集合。 * 開啟檔案:有兩種模式 "rw"讀寫 "r"只讀 * 檔案指標,開啟檔案時指標在開頭pointer = 0; * 寫方法:randomAccessFile.write(int)---->只寫一個位元組(後8位),同時指標指向下一個位元組的位置,準備再次寫入。 * 讀方法:int b = randomAccessFile.read()---->讀一個位元組 * 檔案讀寫完成之後一定要關閉(否則報Oracle官方說明錯誤) */ public class RandomAccessFileTest { public static void main(String[] args) throws Exception { String str = "中國CJL"; File file = new File("/Users/cjl/Downloads/io_test/random_file1.txt"); RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); byte[] bytes = str.getBytes("gbk"); randomAccessFile.write(bytes); System.out.println("當前指標位置:" + randomAccessFile.getFilePointer()); //讀操作,將檔案內容讀取到位元組陣列中 randomAccessFile.seek(0); byte[] readBytes = new byte[(int) randomAccessFile.length()]; //可以一次只讀一個位元組,也可以全部一次性讀取到位元組陣列,讀入到位元組陣列也可以跟起始和結束位置 randomAccessFile.read(readBytes); //以16進位制編碼的形式輸出,一個byte為8位,可用兩個十六進位制位表示 for (byte b : readBytes) { System.out.print(Integer.toHexString(b & 0xff) + " "); } System.out.println(); //轉換成字元輸出,不指定編碼的情況下,結果位亂碼 String result = new String(readBytes); System.out.println("讀取結果:" + result); //轉換成字元輸出,以什麼編碼儲存,就以什麼編碼讀取 String result2 = new String(readBytes, "gbk"); System.out.println("讀取結果:" + result2); randomAccessFile.close(); } } /* * 輸出 * 當前指標位置:7 * d6 d0 b9 fa 43 4a 4c * 讀取結果:�й�CJL * 讀取結果:中國CJL * */
輸出檔案內容: