zoukankan      html  css  js  c++  java
  • JavaSE:RandomAccessFile 类

    RandomAccessFile 类

      1.  基本概念

            java.io.RandomAccessFile类:支持对随机访问文件的读写操作

      2.  常用的方法

            方法声明                                    功能介绍

            RandomAccessFile(String name,String mode)                    根据参数指定的名称和模式构造对象

                                                     r:以只读方式打开

                                                     rw: 打开一遍读取和写入

                                                     rwd:打开以便读取和写入,同步文件内容的更新

                                                     rws: 打开以便读取和写入,同步文件内容和元数据的更新

            int read()                                    读取单个字节的数据

            void seek(long pos)                                用于设置从此文件的开头开始测量的文件指针偏移量

            void write(int b)                                  将参数指定的单个字节写入

            void close()                                     用于关闭流并释放有关的资源

      3.  代码示例

          class RandomAccessFileTest {

            main(String[] args){

              RandomAccessFile raf = null;

              try{

                //  1. 创建RandomAccessFile类型的对象,与d:/a.txt文件关联

                raf = new RandomAccessFile("d:/a.txt","rw");

                //  2. 对文件内容进行随机读写操作

                //  设置距离文件开头位置的偏移量,从文件开头位置向后偏移3个字节  aellhello

                raf.seek(3);

                int res = raf.read();

                System.out.println("读取到的单个字符是:" + (char)res); // a l
                res = raf.read();
                System.out.println("读取到的单个字符是:" + (char)res); // h 指向了e
                raf.write('2'); // 执行该行代码后覆盖了字符'e'
                System.out.println("写入数据成功!");

                } catch (IOException e) {
                  e.printStackTrace();
                } finally {
                  // 3.关闭流对象并释放有关的资源
                  if (null != raf) {
                    try {
                      raf.close();
                    } catch (IOException e) {
                      e.printStackTrace();
                    }
                  }
                }

              }

            }

          } 

    4.  IO流练习

  • 相关阅读:
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/14870050.html
Copyright © 2011-2022 走看看