RandomAccessFile是一个集输入和输出功能的接口,既可以读文件也可以写文件。下面通过RandomAccessFile实现了对文件的内容插入:
package InsertContent;
import java.io.File;
import java.io.RandomAccessFile;
import java.io.FileOutputStream;
import java.io.FileInputStream;
public class InsertContent {
public static void insert(String FileName,long pos,String insertContent) throws Exception{
RandomAccessFile raf=null;
//create a temp file
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);
//put file's pointer to pos
raf.seek(pos);
byte[] buff=new byte[64];
int hasRead=0;
//read data of after pos
while((hasRead=raf.read())>0){
//write data to buff
tmpOut.write(buff,0,hasRead);
}
raf.seek(pos);
//insert String
raf.write(insertContent.getBytes());
while((hasRead=tmpIn.read())>0){
//write original data
raf.write(buff,0,hasRead);
}
}
finally{
raf.close();
}
}
public static void main(String[] args) throws Exception{
insert("InsertContent.java",45,"插入的内容\r\n");
}
}