随机访问流

RandomAccessFile:随机访问流,RandomAcceFile对象内部维护了一个大型的byte数组,通过指针操作数组中的元素,该对象的源或目的只能是文件
构造函数:

RandomAccessFile(String name, String mode),
其中mode为访问限定,“r”表示只读方式,“rw”读写方式,“rws”,“rwd”

特有方法:

·getChannel(),获取当前索引位置,long型
·seek(),带参,调整至参数索引位置
·getFilePointer():获取当前指针位置


简单使用:在一个文件的指定位置插入指定内容

	public static void randomFiile(int pos, String content) {
        try {
            // 创建临时文件,用于保存原文件在pos位置后面的内容
            File temp = File.createTempFile("file", ".tmp", new File("C:\\Users\\阿劼\\Desktop"));
            // 程序运行结束时该临时文件自动删除
            temp.deleteOnExit();

            // 创建关联临时文件的输入输出流
            FileOutputStream outputStream = new FileOutputStream(temp);
            FileInputStream inputStream = new FileInputStream(temp);

            // 关联要操作的源文件
            RandomAccessFile rw = new RandomAccessFile("a.txt", "rw");
            
            // 指针跳到指定位置
            rw.seek(pos);
            
            int tmp;
            // 将指针后面的内容保存到临时文件
            while ((tmp = rw.read()) != -1) {
                outputStream.write(tmp);
            }
            
            // 在指定位置后面插入要加入的内容
            rw.seek(pos);
            rw.write(content.getBytes());
            
            // 将临时文件中的内容再添加到源文件的末尾
            while ((tmp = inputStream.read()) != -1) {
                rw.write(tmp);
            }
            
            outputStream.close();
            inputStream.close();
            rw.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值