RandomAccessFile时Java输入/输出流体系中功能最丰富的文件内容访问类,它提供了众多的方法来访问文件内容,既可以读取文件,也可以向文件输出内容,只能对文件进行操作。
RAF对象包含了一个指针,用以标识当前读写处的位置。
RAF包含了如下两个方法来操作文件记录指针。
long seek(long pos):返回文件记录指针的当前位置
voidseek(long pos):将文件记录指针定位到pos位置
RAF也包含两个构造方法:
RandomAccessFile(File file, String mode)
创建一个随机访问文件流从File参数指定的文件中读取,并可选地写入文件。
RandomAccessFile(String name, String mode)
创建随机访问文件流,以从中指定名称的文件读取,并可选择写入文件。
mode参数指定要打开文件的访问模式,有四种取值:
“r”:只能读;
“w”:只能写;
“rwd”:需要更新要写入存储的文件内容;
“rws”:需要更新要写入的文件的内容及其元数据
例:实现对指定位置的指定文件追加内容
public static void main(String args[]) throws IOException {
raf("D:\\a.txt",100,"*******************插入内容**********************");
}
public static void raf(String fileName,long postion,String insertContent) throws IOException{
//创建临时文件存储被插入文件的插入点后面的内容
File tmp = File.createTempFile("tmp",null);
tmp.deleteOnExit();
RandomAccessFile raf = new RandomAccessFile(fileName,"rw");
FileInputStream tmpIn = new FileInputStream(tmp);
FileOutputStream tmpOut = new FileOutputStream(tmp);
raf.seek(postion);
byte[] buf = new byte[64];
int hasRead = 0;
//读取全部内容到临时文件里
while((hasRead = raf.read(buf)) > 0) {
tmpOut.write(buf, 0, hasRead);
}
raf.seek(postion);
//写入插入内容
raf.write(insertContent.getBytes());
//写入插入点后面内容
while((hasRead = tmpIn.read(buf)) > 0) {
raf.write(buf, 0, hasRead);
}
}```