深入理解JAVA I/O系列四:RandomAccessFile

來源:互聯網
上載者:User

標籤:順序   導致   檔案的   字元   中國   dem   時空   and   dom   

一、簡述

 

這個是JDK上的,我們可以看到它的父類是Object,沒有繼承位元組流、字元流家族中任何一個類。並且它實現了DataInput、DataOutput這兩個介面,也就意味著這個類既可以讀也可以寫。

二、存在的意義

1、是JAVA I/O流體系中功能最豐富的檔案內容訪問類,它提供了眾多方法來訪問檔案內容。

2、由於可以自由訪問檔案的任意位置,所以如果需要訪問檔案的部分內容,RandomAccessFile將是更好的選擇。

3、可以用來訪問儲存資料記錄的檔案,檔案的記錄的大小不必相同,但是其大小和位置必須是可知的。

這個類在很多資料上翻譯成中文都是:隨機訪問檔案,在中文裡,隨機是具有不確定的含義,指一會訪問這裡,一會訪問那裡的意思。如果以這種語義來解釋的話,就會感到很困惑。其實,Random在英文中不僅僅有隨機,還有任意的意思。如果中文名為任意訪問檔案是不是就會更好的理解。任意表示我們可以指定檔案中任何一個位置去操作一個檔案。

三、DEMO示範(1)、寫入檔案
 1 public class RandomAccessFileTest 2 { 3     public static void main(String[] args) throws IOException 4     { 5         RandomAccessFile raf = new RandomAccessFile("d:/data.txt","rw"); 6         Person p = new Person(1001,"xiaoming",1.80d); 7         p.write(raf); 8     } 9 }10 class Person11 {12     int id;13     String name;14     double height;15     public Person()16     {17     }18     public Person(int id, String name, double height)19     {20         this.id = id;21         this.name = name;22         this.height = height;23     }24     25     public void write(RandomAccessFile raf) throws IOException26     {27         raf.write(id);28         raf.writeUTF(name);29         raf.writeDouble(height);30     }31 } 

執行結果:

 

1、執行結果亂碼是由於寫入的是二進位檔案,這個待會我們再使用程式讀取。(這個跟前面介紹的DataInputStream、DataOutputStream類似)

2、第五行中,RandomAccessFile的建構函式除了指定了要寫入了檔案,還有另外一個參數:mod,主要用來指定開啟檔案的訪問模式。

      

3、讀取的方式就是讀取基礎資料型別 (Elementary Data Type),其中第28行使用的方法是:writeUTF(String str)

 使用 modified UTF-8 編碼以與機器無關的方式將一個字串寫入該檔案,這個方法就是將字串寫入檔案,而且不用擔心會出現亂碼,因為使用的編碼方式是UTF-8

 (2)、檔案讀取

由於剛才寫入的是二進位檔案,現在使用程式去讀取檔案:

 

 1 public class RandomAccessFileTest 2 { 3     public static void main(String[] args) throws IOException 4     { 5         RandomAccessFile raf = new RandomAccessFile("d:/data.txt", "rw"); 6         Person p = new Person(1001, "xiaoming", 1.80d); 7         p.write(raf);// 寫入檔案後,任意訪問檔案的指標在檔案的結尾 8  9         raf.seek(0);// 讀取時,將指標重設到檔案的開始位置。10         Person p2 = new Person();11         p2.read(raf);12         System.out.println("id=" + p2.getId() + ";name=" + p2.getName()13                 + ";height=" + p2.getHeight());14 15     }16 }17 class Person18 {19     int id;20     String name;21     double height;22     public Person()23     {24     }25     public Person(int id, String name, double height)26     {27         this.id = id;28         this.name = name;29         this.height = height;30     }31     32     public void write(RandomAccessFile raf) throws IOException33     {34         raf.writeInt(id);35         raf.writeUTF(name);36         raf.writeDouble(height);37     }38     39     public void read(RandomAccessFile raf) throws IOException40     {41         this.id = raf.readInt();42         this.name = raf.readUTF();43         this.height = raf.readDouble();44     }45     public int getId()46     {47         return id;48     }49     public void setId(int id)50     {51         this.id = id;52     }53     public String getName()54     {55         return name;56     }57     public void setName(String name)58     {59         this.name = name;60     }61     public double getHeight()62     {63         return height;64     }65     public void setHeight(double height)66     {67         this.height = height;68     }69     70 } 

執行結果:

id=1001;name=xiaoming;height=1.8

1、在39-43行代碼中,由於是按基礎資料型別 (Elementary Data Type)寫入和讀取,所以在讀取的時候一定嚴格按照寫入的順序。

2、第9行的位置上,由於在寫入的時候,導致訪問的指標的位置在檔案的結尾處,現在讀取的時候,需要將訪問指標的位置重設到檔案開頭處。

 (3)、追加內容
1 public static void main(String[] args) throws IOException2     {3         RandomAccessFile raf = new RandomAccessFile("D:/out.txt","rw");4         raf.seek(raf.length());5         raf.write("\r\n中國移動閱讀基地".getBytes());6     }

執行結果:

1、這段程式示範了在檔案原有內容的基礎上去追加內容。其中seek方法就是將訪問指標移動到檔案內容的末尾。

2、RandomAccessFile依然只能追加,不能像檔案的指定位置插入內容。如果強制將檔案記錄指標移動到中間位置後開始輸出內容,則新的內容會覆蓋檔案中原有的內容。

3、如果需要向檔案指定的位置插入內容,程式需要先把插入點後面的內容讀入緩衝區,等插入完成後,再講緩衝區的內容追加到檔案的後面。

(4)、指定位置插入
 1     public static void main(String[] args) 2     { 3         try 4         { 5             insert("d:/out.txt",5,"插入的內容"); 6         } 7         catch (IOException e) 8         { 9             e.printStackTrace();10         }11     }12     13     private static void insert(String fileName,long pos,String content) throws IOException14     {15         //建立臨時空檔案16         File tempFile = File.createTempFile("temp",null);17         //在虛擬機器終止時,請求刪除此抽象路徑名表示的檔案或目錄18         tempFile.deleteOnExit();19         FileOutputStream fos = new FileOutputStream(tempFile);20         21         RandomAccessFile raf = new RandomAccessFile(fileName,"rw");22         raf.seek(pos);23         byte[] buffer = new byte[4];24         int num = 0;25         while(-1 != (num = raf.read(buffer)))26         {27             fos.write(buffer,0,num);28         }29         raf.seek(pos);30         raf.write(content.getBytes());31         FileInputStream fis = new FileInputStream(tempFile);32         while(-1 != (num = fis.read(buffer)))33         {34             raf.write(buffer,0,num);35         }36     }

執行結果:

1、這裡插入內容的原理就是:先把插入點後面的內容讀入緩衝區,等插入完成後,再講緩衝區的內容追加到檔案的後面。

 

深入理解JAVA I/O系列四:RandomAccessFile

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.