package com.xuan.io;
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{
RandomAccessFile raf=null;
//创建一个临时文件来保存插入点后的数据
File tmp=File.createTempFile("tmp", null);
FileOutputStream tmpOut=null;
FileInputStream tmpIn=null;
tmp.deleteOnExit();
try{
raf=new RandomAccessFile(fileName,"rw");
tmpOut=new FileOutputStream(tmp);
tmpIn=new FileInputStream(tmp);
raf.seek(pos);
//下面代码将插入点后的内容读入临时文件中保存
byte[] bbuf=new byte[64];
//用于保存实际读取的字节数
int hasRead=0;
//使用循环方式读取插入点后的数据
while((hasRead=raf.read(bbuf))>0){
//将读取的数据写入临时文件
tmpOut.write(bbuf,0,hasRead);
}
//下面代码插入内容
//把文件记录指针重新定位到pos位置
raf.seek(pos);
//追加需要插入的内容
raf.write(in
(45)使用RandomAccessFile向中间部分插入内容防止覆盖后面的内容方法
本文介绍如何使用Java的RandomAccessFile类在文件的中间位置插入内容,而不覆盖后面的数据。通过创建临时文件保存插入点之后的数据,然后在原文件中插入新内容,并追加临时文件内容来实现。
摘要由CSDN通过智能技术生成