天天看点

IO流(RandomAccessFile)

  • RandomAccessFile
  • 1:随机访问文件,自身具备读写的方法
  • 2:通过skipBytes(int x),seek(int x)来达到随机访问。

RandomAccessFile-写入

public class Io59_1 {
    public static void main(String[] args) throws IOException {
        /*
         * RandomAccessFile
         * 
         * 特点:
         * 1,该对象即能读,又能写
         * 2,该对象内部维护了一个byte数组,并通过指针可以操作数组中的元素
         * 3,可以通过getFilePointer方法获取指针的位置,和通过seek方法设置指针的位置。
         * 4,其实该对象就是对字节输出流和输入流的封装。
         * 5,该对象的源或者目的只能是文件,通过构造就可以看出(APi)
         * */
        writeFile();

    }

    //使用RandomAccessFile对象写入一些人员信息,比如姓名和年龄

    public static void writeFile() throws IOException{
        /*
         * 如果文件不存在,则创建,如果文件存在,不创建
         * */
        RandomAccessFile raf=new RandomAccessFile("ranacc.txt", "rw");
        raf.write("张三".getBytes());
        raf.writeInt();
        raf.write("小强".getBytes());
        raf.writeInt();

    }
}
           

RandomAccessFile-读取&随机读取

public class Io60_1 {
    public static void main(String[] args) throws IOException {
        readFile();
    }

    private static void readFile() throws IOException {
        /*
         * RandomAccessFile的读取方式。是按照指针的位置去读取的。不指定指针的位置。指针从0开始读取值。
         * 需求:不读取第一个值。直接读取第二个值。这时候就需要用seek()去指定指针的位置。
         * 
         * getFilePointer()可以获取当前指针在什么位置
         * */


        RandomAccessFile raf=new RandomAccessFile("ranacc.txt", "r");

        //通过seek设置指针的位置
        raf.seek(*);//随机的读取

        byte[] buf=new byte[];
        raf.read(buf);
        String name=new String(buf);

        int age=raf.readInt();

        System.out.println("name="+name);
        System.out.println("age="+age);
        System.out.println("pos:"+raf.getFilePointer());

        raf.close();

    }
}
           

RandomAccessFile-随机写入&细节

public class Io61_1 {
    public static void main(String[] args) throws IOException {
        randomWrite();
    }

    private static void randomWrite() throws IOException {
        RandomAccessFile raf=new RandomAccessFile("ranacc.txt", "rw");

        /*
         * 如果文件存在,不创建。当我们往已有数据的文件中写入数据的时候,会根据角标的位置
         * 去覆盖原来有的数据。本来没有的数据,就会直接写入。
         * */

        //往指定位置写入数据。
        raf.seek(*);
        raf.write("哈哈".getBytes());
        raf.writeInt();

        raf.close();


    }
}