java-文件操作RandomAccessFile

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileDemo {
    public static void main(String[] args) throws IOException {
        RandomAccessFile rdf=new RandomAccessFile("max.txt","rw");
        /**寫入int最大值*/
        int imax=Integer.MAX_VALUE;
        rdf.write(imax>>>24);
        rdf.write(imax>>>16);
        rdf.write(imax>>>8);
        rdf.write(imax);
//      rdf.writeInt(imax);//相當於上面4句
        /**
         * seek方法
         * void seek(long pos)
         * 用於移動當前RandomAccessFile的指針位置
         */
        rdf.seek(0);
        /**
         * long getFilePointer()
         * 用於獲取當前RandomAccessFile的指針位置
         */

        System.out.println("寫入完畢");
        /**
         * int readInt()
         * 連續讀取4個字節並返回該int值
         * 若在讀取4個字節的過程中讀取到了文件末尾則會拋出異常EOFException
         * EOF(end of file)
         */
        System.out.println("pos:"+rdf.getFilePointer());// pos:0
        System.out.println("讀取:"+rdf.readInt());//讀取:2147483647
        System.out.println("pos:"+rdf.getFilePointer());//pos:4   因爲int是4個字節
        rdf.seek(0);
        System.out.println("讀取:"+rdf.read());//127 讀取的是byte的最大值
        System.out.println("pos:"+rdf.getFilePointer());//pos:1
        System.out.println("讀取:"+rdf.read());//255
        System.out.println("pos:"+rdf.getFilePointer());//pos:2
//      System.out.println("讀取:"+rdf.readInt());//指針走到文件末尾。出錯拋出異常:java.io.EOFException
        rdf.seek(0);
        rdf.close();

        /**
         * String提供了方法可以將當前字符串轉換爲一組字節
         * byte[] getBytes()
         * 按照系統默認字符集轉換爲一組字節
         *  int read(byte[] b) 
         * 將最多 b.length 個數據字節從此文件讀入 byte 數組。 
         */
        RandomAccessFile raf=new RandomAccessFile("raf.txt","rw");
        String str="hello word!";
        /**字符串寫入**/
        byte[] date1=str.getBytes();//11個。字符
        raf.write(date1);
        raf.write("大家好!".getBytes("utf-8"));
        System.out.println("字符串寫入完畢");
        raf.seek(0);
        //解析字符串並讀取
        byte[] date2=new byte[(int) raf.length()];
        int len=raf.read(date2);//實際讀取的數據字節
        String ss=new String(date2,0,len,"utf-8");
        System.out.println("讀取結果:"+ss);
        raf.close();








    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章