【java io】RandomAccessFile(随机访问文件)和随机位置写入数据

RandomAccessFile(随机访问文件)

RandomAccessFile该对象并不是流体系中的一员,其封装了字节流,封装了一个字节流缓冲区,通过内部的指针来操作数组中的数据

1、特点

1、主要用来操作文件,构造函数只接受两种类型的参数:通过字符串路径,通过File对象
2、该对象可以对文件进行读操作,也可以对文件进行写操作,在对象实例化时需要指定操作模式(r,rw)

2、构造函数

public RandomAccessFile(String name,String mode)
public RandomAccessFile(File file,String mode)

mode各个参数详解
r 代表以只读方式打开指定文件
rw 以读写方式打开指定文件(常用)
rws 读写方式打开,并对内容或元数据都同步写入底层存储设备
rwd 读写方式打开,并对文件内容的更新同步更新至底层存储设备

3、特有方法

//void seek(long pos) 将文件记录指针定位到pos的位置
//void seek(long pos)返回文件记录指针的当前位置
之前io流实现类:新打开的流:写操作默认覆盖原数据,从原数据的第0号位置开始写(就算设为true,也是append,追加)
读操作,默认从0号位置(起始位置)开始读

4、使用

因为这个类特有的方法,可以实现文件读取任意位置数据和在任意位置写入数据和追加数据

import java.io.*;

public class RandomAccessFileDome {
    public static void main(String[] args) {
        String path = "C:\\Users\\Administrator\\Desktop\\Test.txt";
        //randomReader(path, 4);
        //randomWrite(path, "danvknja");
        randomInsert(path ,6,"hello");

//        try {
//            RandomAccessFile rw = new RandomAccessFile(path, "rw");
//            //void seek(long pos) 将文件记录指针定位到pos的位置
//            rw.seek(4);
//            //返回文件记录指针的当前位置
//            rw.getFilePointer();
//
//            rw.close();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

    }

    //读取任意位置的数据
    public static void randomReader(String path, int postion) {
        try {
            RandomAccessFile accessFile = new RandomAccessFile(path, "r");
            //获取文件的初始指针
            System.out.println(accessFile.getFilePointer());

            //将文件指针位置移动到指定位置
            accessFile.seek(postion);
            byte[] bytes = new byte[100];
            int len;
            //循环读取
            while ((len = accessFile.read(bytes)) != -1) {
                System.out.println(new String(bytes, 0, len));
            }
            //关闭资源
            accessFile.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //数据追加
    public static void randomWrite(String path, String content) {
        try {
            RandomAccessFile rw = new RandomAccessFile(path, "rw");

            //文件指针指到末尾
            rw.seek(rw.length());

            rw.write(content.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //任意位置插入

    /**
     * 任意位置插入
     *
     * @param path          文件的路径
     * @param points        指定位置
     * @param insertContent 插入的内容
     */
    public static void randomInsert(String path, long points, String insertContent) {
        RandomAccessFile rw = null;
        BufferedReader reader = null;
        BufferedWriter writer = null;
        File temp = null;
        try {
            rw = new RandomAccessFile(path, "rw");
            temp = File.createTempFile("save", "null");//创建临时文件
            //prefix -- 前缀字符串定义的文件名;必须至少有三个字符长
            //suffix -- 后缀字符串定义文件的扩展名;如果为null后缀".tmp" 将被使用
            reader = new BufferedReader(new FileReader(temp));//临时文件的读取
            writer = new BufferedWriter(new FileWriter(temp)); //临时文件的写入
            rw.seek(points );
            byte[] bytes = new byte[100];
            int num = 0;
            while ((num = rw.read(bytes)) != -1) {
                writer.write(new String(bytes, 0, num));
                System.out.println("已被写入临时文件");
            }
            writer .flush() ;//如果不写这句文件将读不了
            rw.seek(points);
            rw.write(insertContent.getBytes());


            // rw.seek(points +insertContent .length() );
            String amp=null;
            while ((amp  = reader.readLine() ) != null) {
                System.out.println(amp );
                rw.write(amp.getBytes() );
                System.out.println("临时文件已被读取");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                writer .close() ;
                reader.close();
                rw.close();
                temp.deleteOnExit();//关闭流操作和删除临时文件
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值