Java IO流 序列三:RandomAccessFile類

 

3. RandomAccessFile

3.1 RandomAccessFile類簡介

  •        1. Java提供的對文件內容的訪問,既能夠讀文件,也能夠寫文件數組

  •        2. 能夠隨機訪問文件,能夠訪問文件的任意位置dom

  •        3. 讀寫方式:rw(可讀寫) r(只讀)spa

          例:RandomAccessFile raf = new RandomAccessFile(file,"rw")指針

  •        4. 因爲是隨機訪問,該類提供了一個指針,默認打開文件的時候指正文件在開頭 pointer = 0get

  •        5. 寫方法it

            raf.write(int) -->只寫一個字節(8),同時,指針指向下一個位置,準備再次寫入io

  •        6. 讀方法file

            int b = raf.read() -->讀一個字節方法

  •        7. 文件讀寫完成必定要關閉demo

 

 

3.2 示例

public static void main(String[] args) throws Exception {

         // 建立目錄

         File demo = new File("Demo");//未指定絕對路徑,默認是本項目下

         if(!demo.exists()){

              demo.mkdir();

         }

         // 建立文件

         File file = new File(demo,"raf.dat");//demo目錄下建立raf.dat文件

         if(!file.exists()){

              file.createNewFile();

         }

        

         RandomAccessFile raf = new RandomAccessFile(file, "rw");

         // 指針位置

         System.out.println("起始指針位置:" + raf.getFilePointer()); // 0

        

         // 寫操做

         raf.write('A'); //只寫了一個字節

         System.out.println("寫入一次後的指針位置:" + raf.getFilePointer()); // 1

         raf.write('B');

         System.out.println("寫入兩次後的指針位置:" + raf.getFilePointer()); // 2

        

         // 最大整數

         int i = 0x7fffffff;

         // write方法每次只能寫入一個字節,若是要把i寫進去就得寫4

         raf.writeInt(i >>> 24); //8

         raf.writeInt(i >>> 16); //8

         raf.writeInt(i >>> 8);

         raf.writeInt(i); //最後8

         System.out.println("指針位置:" + raf.getFilePointer());  // 18

        

         // 寫入中文

         String s = "";

         byte[] bytes = s.getBytes("utf8");

         raf.write(bytes);

         System.out.println("指針位置:" + raf.getFilePointer());   // 21  

        

         // 文件長度

         System.out.println(raf.length());

        

         // 讀文件. 必須把指針移到頭部

         raf.seek(0);

        

         // 一次性讀取,把文件中的內容所有讀取到字節數組中

         byte[] buf = new byte[(int)raf.length()];

         raf.read(buf);

         System.out.println(Arrays.toString(buf));

        

         raf.close();

     }

相關文章
相關標籤/搜索