java基礎知識回顧之javaIO類--RandomAccessFile類

來源:互聯網
上載者:User

標籤:des   cWeb   style   blog   http   color   java   使用   

java.io
類 RandomAccessFile
java.lang.Object    java.io.RandomAccessFile
1.該類不是IO流中的子類。
2.該類既能讀又能寫。
3.該對象內部分裝了一個位元組數組,通過指標可以運算元組中的元素。
4.其實該對象就是將位元組輸入資料流和輸出資料流進行了封裝。
5.該對象只能對檔案操作,目的和源只能是檔案對象。通過看構造方法可以看得出來。
RandomAccessFile(File file, String mode)
RandomAccessFile(String name, String mode)
普通方法:

public void seek(long pos) throws IOException   設定指標的初始位置
public long getFilePointer()throws IOException 返回指標的位置,就是從開頭的位移量,以位元組為單位。


mode 參數指定用以開啟檔案的訪問模式:

含意

"r" 以唯讀方式開啟。調用結果對象的任何 write 方法都將導致拋出 IOException
"rw" 開啟以便讀取和寫入。如果該檔案尚不存在,則嘗試建立該檔案。
"rws" 開啟以便讀取和寫入,對於 "rw",還要求對檔案的內容或中繼資料的每個更新都同步寫入到底層存放裝置。
"rwd"   開啟以便讀取和寫入,對於 "rw",還要求對檔案內容的每個更新都同步寫入到底層存放裝置。
代碼:
在ranacc.txt寫入,張三,97,王強,99
    //使用RandomAccessFile對象寫入一些人員資訊,比如姓名和年齡。    public static void writeFile() throws IOException{        /*         * 如果檔案不存在,則建立,如果檔案存在,不建立         *          */        RandomAccessFile raf = new RandomAccessFile("ranacc.txt","rw");        raf.write("張三".getBytes());        raf.writeInt(97);        raf.write("小強".getBytes());        raf.writeInt(99);//                raf.close();    }

在RandomAccessFile對象的位元組數組中存放如所示:

漢字為兩個位元組,數字為一個位元組:

然後需求要求讀小強的資訊,把小強,99輸出。

這就用到RandomAccessFile對象中的seek方法。


/**     * 讀取小強的資訊,而不是張三的資訊     * @throws IOException     */    public static void readFile() throws IOException {                RandomAccessFile raf = new RandomAccessFile("ranacc.txt", "r");                //通過seek設定指標的位置。        raf.seek(1*8);//隨機的讀取。只要指定指標的位置即可。                 byte[] buf = new byte[4];        raf.read(buf);                String name = new String(buf);//                int age = raf.readInt();//從當前指標開始讀4個位元組                System.out.println("name="+name);        System.out.println("age="+age);                System.out.println("pos:"+raf.getFilePointer());//擷取指標的位置                raf.close();                    }

輸出:

name=小強
age=99
pos:16

結論:隨機讀取,可以讀取位元組數組中的任意一個位置的資料。


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.