• RandomAccessFile


    RandomAccessFile:

    特点:

    1:该对象即可读取,又可写入。

    2:该对象中的定义了一个大型的byte数组,通过定义指针来操作这个数组。

    3:可以通过该对象的getFilePointer()获取指针的位置,通过seek()方法设置指针的位置。

    4:该对象操作的源和目的必须是文件。

    5:其实该对象内部封装了字节读取流和字节写入流。

    注意:实现随机访问,最好是数据有规律。

    class RandomAccessFileDemo{

        public static void main(String[] args) throws IOException{

           write();

           read();

           randomWrite();

        }

        //随机写入数据,可以实现已有数据的修改。

        public static void randomWrite()throws IOException{

           RandomAccessFile raf = new RandomAccessFile("random.txt","rw");

           raf.seek(8*4);

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

           raf.write("王武".getBytes());

           raf.writeInt(102);

           raf.close();

        }

        public static void read()throws IOException{

           RandomAccessFile raf = new RandomAccessFile("random.txt","r");//只读模式。

           //指定指针的位置。

           raf.seek(8*1);//实现随机读取文件中的数据。注意:数据最好有规律。

           System.out.println("pos1 :"+raf.getFilePointer());

           byte[] buf = new byte[4];

           raf.read(buf);

           String name = new String(buf);

           int age = raf.readInt();

           System.out.println(name+"::"+age);

           System.out.println("pos2 :"+raf.getFilePointer());

           raf.close();

        }

        public static void write()throws IOException{

           //rw:当这个文件不存在,会创建该文件。当文件已存在,不会创建。所以不会像输出流一样覆盖。

           RandomAccessFile raf = new RandomAccessFile("random.txt","rw");//rw读写模式

           //往文件中写入人的基本信息,姓名,年龄。

           raf.write("张三".getBytes());

           raf.writeInt(97);

           raf.close();

        }

    }

  • 相关阅读:
    C++内存分配
    扩展哈夫曼编码
    用递归函数和栈操作逆序一个栈
    非递归遍历二叉树
    malloc/free和new/delete
    洗牌算法及其证明
    野指针问题
    计算编辑距离
    数组指针/指针数组的使用
    sizeof/strlen/length
  • 原文地址:https://www.cnblogs.com/wqing7/p/5896112.html
Copyright © 2020-2023  润新知