欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-21 20:32:10
复制代码 代码如下:import java.io.file;import java.io.fileinputstream;import java.io.fileoutput...

复制代码 代码如下:

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");
    }
}