RandomAccessFile类是一个可以进行随机读写的java类,可以动态的移动指针进行随机写

构造函数信息:

主要方法: 如果在seek方法设置的位置的上进行写内容会覆盖当年位置上的内容

package cn.bean.demo.random;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileTest {
public static void main(String[] args) {
testRandomReadWrite();
}
static void testRandomReadWrite(){
//创建一个随机读写的实例[rw代表读写;r代表只读,不能写]
try (RandomAccessFile accessFile=new RandomAccessFile("String1.txt", "rw");)
{
//在文件的第二行内容中插入 hello china
//读取第一行内容,并把指针移到第一行尾部
String line=accessFile.readLine();
//读取剩余内容放入到一个缓冲区中[如果文件内容过大会导致内存占用量过大,应该把剩余内容写入到一个磁盘文件中,所以随机插入的时候最好要判断一下文件的大小,在做处理]
byte[] buff=new byte[(int) (accessFile.length()-line.length())];
//读取剩余内容到buff中
accessFile.read(buff);
//读完之后指针在文件末尾处,插入前先移动指针位置
accessFile.seek(line.length());
//插入hello china
accessFile.writeBytes("
hello china
");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}