构造函数
RandomAccessFile(String name, String mode)
RandomAccessFile(File file, String mode)
第一个参数指定路径可以是String类型或者File类型
第二个参数mode指定访问形式
mode有四种:
1."r":以只读形式打开,调用任何write方法都会报错
2.“rw”:进行读取和写入
3.“rws”:进行读取和写入,对文件内容和元数据的每次更新都会写入到基础存储设备
4.“rwd”:进行读取和写入,对文件内容的每次更新都会写入到基础存储设备
RandonAccessFile是IO体系中功能最丰富的文件访问类,既可以读取文件内容,也可以向文件中写入内容,同时,程序可以直接调到文件的任意位置进行读取操作
特殊方法:
任意位置读写:
long getFilePointer() 返回当前文件的位置
void seek(long pos) 将文件记录指针定位到指定位置pos
String path="E:\\java\\IO\\IOTest\\test2.txt";
try {
RandomAccessFile randomAccessFile = new RandomAccessFile(path, "rw");
System.out.println("第一次获取指针的位置:"+randomAccessFile.getFilePointer());
//相关写操作
randomAccessFile.write("hello world".getBytes());
//String的getBytes()方法是得到一个操作系统默认的编码格式的字节数组
System.out.println("第二次获取指针的位置:"+randomAccessFile.getFilePointer());
//移动指针
randomAccessFile.seek(0);
System.out.println("第三次获取指针的位置:"+randomAccessFile.getFilePointer());
randomAccessFile.write("tulun".getBytes());
System.out.println("第四次获取指针的位置:"+randomAccessFile.getFilePointer());
randomAccessFile.seek(0);
//读取操作
byte[] bytes=new byte[100];
int read = randomAccessFile.read(bytes);
System.out.println("读取内容:"+new String(bytes,0,read));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
课堂练习:
/**
* 内容增加
* @param source:原文件位置
* @param index:指定插入位置
* @param content:待插入内容
*/
public static void randomIndexContent(String source,Integer index,String content) {
/**
* 思路
* 1、通过seek方法跳转到指定位置
* 2、将指定位置的内容读取出来
* 3、在通过seek方法跳转到指定位置
* * 4、将追加内容进行写入
* * 5、将读取出来的内容写入到原文件中
*/
File file = new File(source);
//参数校验
if (!file.exists() || (file.exists() && file.isDirectory())) {
System.out.println("原文件不存在");
return;
}
if (file.length() < index) {
System.out.println("位置越界");
return;
}
RandomAccessFile sourceFile = null;
String tmpPath = file.getParent() + File.separator + "tmp";
//处理零时文件 deleteOnExit,程序退出即删除
File file1 = new File(tmpPath);
file1.deleteOnExit();//处理临时文件是用 deleteOnExit 方法,当程序退出虚拟机即程序结束时删除文件
RandomAccessFile tmpFile = null;
try {
sourceFile = new RandomAccessFile(file,"rw");
tmpFile = new RandomAccessFile(file1,"rw");
//跳转到指定位置
sourceFile.seek(index);
//循环读取后续内容
byte[] bytes = new byte[1024];
int len = 0;
while ((len = sourceFile.read(bytes,0,1024)) != -1) {
tmpFile.write(bytes,0,len);
}
//跳转到指定位置
sourceFile.seek(index);
//追加内容
sourceFile.write(content.getBytes());
//将临时文件内容写入
tmpFile.seek(0);
while ((len = tmpFile.read(bytes,0,1024)) != -1) {
sourceFile.write(bytes,0,len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (sourceFile != null) sourceFile.close();
if (tmpFile != null) tmpFile.close();
} catch (Exception e){}
}
}