简介
RandomAccessFile的唯一父类是Object,与其他流父类不同。是用来访问那些保存数据记录的文件的,这样你就可以用seek( )方法来访问记录,并进行读写了。这些记录的大小不必相同;但是其大小和位置必须是可知的。
说明
(1)指针
RandomAccessFile文件记录指针方法
long getFilePointer():返回文件记录指针的当前位置
void seek(long pos):将文件记录指针定位到pos位置
(2)访问模式
r:以只读方式打开指定文件。如果试图对该RandomAccessFile指定的文件执行写入方法则会抛出IOException;
rw:以读取、写入方式打开指定文件。如果该文件不存在,则尝试创建文件;
rws:以读取、写入方式打开指定文件。相对于rw模式,还要求对文件的内容或元数据的每个更新都同步写入到底层存储设备;
rwd:与rws类似,只是仅对文件的内容同步更新到磁盘,而不修改文件的元数据
简单示例
仅供参考,未做异常处理和io关闭操作。
文本追加
public static void main(String[] args) throws Exception {
String content = "\n现在的女孩都很现实";
String filePath = "D:/test.txt";
//文本追加插入
simpleInsert(filePath,content);
}
private static void simpleInsert(String filePath,String content) throws Exception {
RandomAccessFile raf = new RandomAccessFile(filePath,"rw");
raf.seek(raf.length());
raf.write(content.getBytes());
print(filePath);
}
private static void print(String filePath) throws IOException {
FileReader fileReader = new FileReader(filePath);
BufferedReader br = new BufferedReader(fileReader);
String s;
while ((s = br.readLine()) != null) {
System.out.println(s);
}
fileReader.close();
}

指定位置插入
如果需要向文件指定的位置插入内容,程序需要先把插入点后面的内容读入缓冲区,等插入完成后,再讲缓冲区的内容追加到文件的后面。
public static void main(String[] args) throws Exception {
String content = "大多";
String filePath = "D:/test.txt";
//指定位置插入
pointerInsert(filePath,28,content);
}
private static void pointerInsert(String filePath,int pos, String content) throws Exception{
//创建临时目录
File tempFile = File.createTempFile("temp",null);
tempFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tempFile);
RandomAccessFile raf = new RandomAccessFile(filePath,"rw");
//读取指定位置后文本到缓存文件中
raf.seek(pos);
byte[] buffer = new byte[64];
int num = 0;
while(-1 != (num = raf.read(buffer))) {
fos.write(buffer,0,num);
}
//在指定位置插入文本后,再追加缓存文件的文本
raf.seek(pos);
raf.write(content.getBytes());
FileInputStream fis = new FileInputStream(tempFile);
while(-1 != (num = fis.read(buffer))) {
raf.write(buffer,0,num);
}
print(filePath);
}
private static void print(String filePath) throws IOException {
FileReader fileReader = new FileReader(filePath);
BufferedReader br = new BufferedReader(fileReader);
String s;
while ((s = br.readLine()) != null) {
System.out.println(s);
}
fileReader.close();
}

本文介绍了RandomAccessFile,其唯一父类是Object,用于访问保存数据记录的文件,可通过seek()方法访问记录。说明了其文件记录指针方法和访问模式,还给出简单示例,包括文本追加和指定位置插入,指定位置插入需先将插入点后内容读入缓冲区再追加。
636

被折叠的 条评论
为什么被折叠?



