RandomAccessFile类

一. RandomAccessFile类介绍:

1. RandomAccessFile类既可以读取文件内容,也可以向文件输出数据

2. RandomAccessFile类支持“随机访问”的方式,程序可以直接跳到文件的任意地方来读写文件

    2.1 支持只访问文件的部分内容

    2.2 可以向已存在的文件后追加内容

3. RandomAccessFile对象包含一个记录指针,用以标示当前读写出的位置。RandomAccessFile类对象可以自由移动记录指针:

    3.1 long getFilePointer():获取文件记录指针的当前位置

    3.2 void seek(long pos):将文件记录指针定位到pos位置

4. 创建RandomAccessFile类可以指定一个mode参数,该参数指定RandomAccessFile的访问模式:

    4.1 r:以只读方式打开

    4.2 rw:以读、写方式打开

二. 示例代码

package test.com.atguigu.javase.lesson10; 

import org.junit.Test;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileTestTest {

    @Test
    public void testRandomAccessFile() throws IOException {
        //1.创建RandomAccessFile对象
        RandomAccessFile access = new RandomAccessFile("hello.txt", "rw");

        //2.对文件进行读写操作
        //读
        String str = null;
        while((str = access.readLine()) != null){
            System.out.println(str);
        }
        //向文件结尾写入
        access.writeBytes("www.atguigu.com");

        //设置指针位置
        access.seek(20);
        //向指定位置写入字符串:把原有的文件内容覆盖了
        access.writeBytes("insert");

        //3.关闭RandomAccessFile对象
        access.close();
    }

    /**
     * 使用RandomAccessFile
     * 向hello.txt文件中插入一行:I love Gongfu...
     * 原文件内容下移
     */
    @Test
    public void testRandomAccessFile2() throws IOException {
        //1.创建RandomAccessFile对象
        RandomAccessFile access = new RandomAccessFile("hello.txt","rw");
        //2.先读第一行
        String lineOne = access.readLine();
        //3.把第一行后面的内容先读取到一个byte数组中
        byte[] buffer = new byte[(int) (access.length() - lineOne.length())];
        access.read(buffer);
        //4.指针移动到写位置
        access.seek(lineOne.length());
        //5.写入要写的字符串
        access.writeBytes("\nI Love Gongfu...\n");
        //6.在写入先前的内容
        access.read(buffer);
        //7.关闭RandomAccessFile对象
        access.close();
    }
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值