17.4.18 RandomAccessFile类
(1)基本概念
java.io.RandomAccessFile类主要支持对随机访问文件的读写操作。
(2)常用的方法
方法声明 功能介绍RandomAccessFile(String name, Stringmode)根据参数指定的名称和模式构造对象r: ``以只读方式打开rw``:打开以便读取和写入rwd:``打开以便读取和写入,同步文件内容的更新rws:打开以便读取和写入,同步文件内容和元数据的更新int read()读取单个字节的数据void seek(long pos)用于设置从此文件的开头开始测量的文件指针偏移量void write(int b)将参数指定的单个字节写入void close()用于关闭流并释放有关的资源
执行代码
package com.lagou.task17;import java.io.IOException;import java.io.RandomAccessFile;public class RandomAccessFileTest {public static void main(String[] args) {RandomAccessFile raf = null;try {// 1.创建RandomAccessFile类型的对象与d:/a.txt文件关联raf = new RandomAccessFile("d:/a.txt", "rw");// 2.对文件内容进行随机读写操作// 设置距离文件开头位置的偏移量,从文件开头位置向后偏移3个字节 aellhelloraf.seek(3);int res = raf.read();System.out.println("读取到的单个字符是:" + (char)res); // a lres = raf.read();System.out.println("读取到的单个字符是:" + (char)res); // h 指向了eraf.write('2'); // 执行该行代码后覆盖了字符'e'System.out.println("写入数据成功!");} catch (IOException e) {e.printStackTrace();} finally {// 3.关闭流对象并释放有关的资源if (null != raf) {try {raf.close();} catch (IOException e) {e.printStackTrace();}}}}}
