4.4 RandomAccessFile

       Instances of this class support both reading and writing to a
random access file.
       RandomAccessFile的实例可以始些对文件中随机位置的读写。

4.4.1 RandomAccessFile主要方法介绍

  1. f.seek()
    获取当前文件指向的位置,读写都是一样的。
  2. f.read(byte[]) 和 f.readFully(byte[] )
    读文件数据到缓冲区,二者区别是readFully会把缓冲区读满,如果读不满则抛出异常。
  3. f.wrete(byte[])
    往文件中写入数据,写入的位置为seek() 指定的位置。


4.4.2 RandomAccessFile的使用

       创建实例,指定路径,指定读写模式,rw表示可读可写

RandomAccessFile file = new RandomAccessFile("nio\\temp.txt",
            "rw");

       完整实例,使用RandomAccessFile的精髓就在于使用seek方法调整实例当前指针位置。

RandomAccessFile file = new RandomAccessFile("D:\\company\\myself\\app-server\\app-server\\src\\main\\java\\com\\example\\appserver\\nio\\temp.txt",
            "rw");
    //从0开始读数据
    byte[] f = new byte[1000];
    file.read(f);
    System.err.println(new String(f,StandardCharsets.UTF_8));
    //从指定位置开始读数据
    file.seek(50);
    file.read(f);
    System.err.println(new String(f,StandardCharsets.UTF_8));
    //使用readFully
    try {
        file.readFully(f);
    }catch (Exception e){
        e.printStackTrace();
    }
    System.err.println(new String(f,StandardCharsets.UTF_8));

    //往文件开头写数据
    file.write("lbh".getBytes());
    //往文件指定位置写入数据
    file.seek(file.length());
    file.write("\r\nshow".getBytes());