java randomaccessfile使用方法 java使用randomaccessfile在文件任意位置写入数据

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

java randomaccessfile使用方法 java使用randomaccessfile在文件任意位置写入数据

  2021-03-19 我要评论
想了解java使用randomaccessfile在文件任意位置写入数据的相关内容吗,在本文为您仔细讲解java randomaccessfile使用方法的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:randomaccessfile,文件任意位置,下面大家一起来学习吧。

复制代码 代码如下:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;


public class InsertContent {
    public static void insert(String fileName, long pos, String insertContent) throws IOException{
        File file = File.createTempFile("tmp", null);
        file.deleteOnExit();
        RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
        FileInputStream fileInputStream = new FileInputStream(file);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        raf.seek(pos);
        byte[] buff = new byte[64];
        int hasRead = 0;
        while((hasRead = raf.read(buff)) > 0){
            fileOutputStream.write(buff);
        }
        raf.seek(pos);
        raf.write(insertContent.getBytes());
        //追加文件插入点之后的内容
        while((hasRead = fileInputStream.read(buff)) > 0){
            raf.write(buff, 0, hasRead);
        }
        raf.close();
        fileInputStream.close();
        fileOutputStream.close();
    }
    public static void main(String[] args) throws IOException {
        insert("F:\AttendanceActivity.java", 57, "插入的内容rn");
    }
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们