java-IO流-在文件中数据内容的插入问题

1问题

在某个文件的中间某个位置插入字符串,例如:

文件内容:abcd

插入内容:123

插入下标:2

预期结果:ab123cd

2基本思路

1、校验参数的合法性
2、将指针移动到插入的位置
3、通过流读取出来写到磁盘文件上(开辟读和写的流)
4、将指针重新指定到插入位置
5、将写入的内容write写入
6、将后续内存重新写入该文件

3代码演示

import java.io.*;

public class InsertTest {
//1、校验参数的合法性
//2、将指针移动到插入的位置
//3、通过流读取出来写到磁盘文件上(开辟读和写的流)
//4、将指针重新指定到插入位置
//5、将写入的内容write写入
//6、将后续内存重新写入该文件
    
//    方法: void seek(long pos) //将文件记录移动到指定的pos位置
    public static void insertContent(String path  , int index, String cont) {
        //1、校验参数的合法性
        File file = new File(path);
        if(!file.exists()){
            return;
        }
        if(index <0){
            return;
        }

        File tmpfile = new File(file.getParent()+file.separator+file.separator+"tmp.txt");
        //新建一个文件tmp.txt来存放需要移动的内容
        RandomAccessFile randomAccessFile = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            randomAccessFile = new RandomAccessFile(path, "rws");
            //2、将指针移动到插入的位置
            randomAccessFile.seek(index);
            //3、通过流读取出来写到磁盘文件上(开辟读和写的流)
            outputStream = new FileOutputStream(tmpfile);
            inputStream = new FileInputStream(tmpfile);
            byte[] bytes = new byte[100];
            int len;
            while ((len = randomAccessFile.read(bytes)) !=-1){
                outputStream.write(bytes,0,len);
            }
            outputStream.flush();
            //4、将指针重新指定到插入位置
            randomAccessFile.seek(index);
            //5、将写入的内容write写入
            randomAccessFile.write(cont.getBytes());
            //6、将后续内存重新写入该文件
            while ((len =inputStream.read(bytes)) !=-1) {
                randomAccessFile.write(bytes,0,len);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            try {
                //关闭所有的流
            if (randomAccessFile != null) {
                randomAccessFile.close();
            }
            if(inputStream != null){
                inputStream.close();
            }
            if(outputStream!=null){
                outputStream.close();
            }
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
        }

    }
    public static void main(String[] args) throws IOException {
        insertContent("C:\\Users\\ccc\\Desktop\\IO流\\b.txt",2,"123");
        //参数path:文件路径;index:插入下标;cont:插入字符串
    }
}

4运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值