RandomAccessFile:随机访问流,RandomAcceFile对象内部维护了一个大型的byte数组,通过指针操作数组中的元素,该对象的源或目的只能是文件
构造函数:
RandomAccessFile(String name, String mode),
其中mode为访问限定,“r”表示只读方式,“rw”读写方式,“rws”,“rwd”
特有方法:
·getChannel(),获取当前索引位置,long型
·seek(),带参,调整至参数索引位置
·getFilePointer():获取当前指针位置
简单使用:在一个文件的指定位置插入指定内容
public static void randomFiile(int pos, String content) {
try {
// 创建临时文件,用于保存原文件在pos位置后面的内容
File temp = File.createTempFile("file", ".tmp", new File("C:\\Users\\阿劼\\Desktop"));
// 程序运行结束时该临时文件自动删除
temp.deleteOnExit();
// 创建关联临时文件的输入输出流
FileOutputStream outputStream = new FileOutputStream(temp);
FileInputStream inputStream = new FileInputStream(temp);
// 关联要操作的源文件
RandomAccessFile rw = new RandomAccessFile("a.txt", "rw");
// 指针跳到指定位置
rw.seek(pos);
int tmp;
// 将指针后面的内容保存到临时文件
while ((tmp = rw.read()) != -1) {
outputStream.write(tmp);
}
// 在指定位置后面插入要加入的内容
rw.seek(pos);
rw.write(content.getBytes());
// 将临时文件中的内容再添加到源文件的末尾
while ((tmp = inputStream.read()) != -1) {
rw.write(tmp);
}
outputStream.close();
inputStream.close();
rw.close();
} catch (Exception e) {
e.printStackTrace();
}
}