如题
/*
实现RandomAccessFile“插入”数据的操作
*/
@Test
public void test02(){
RandomAccessFile raf = null;
try {
//1.
raf = new RandomAccessFile("Hello.txt","rw");
//2.
//2.1将指针调到角标为3的位置
raf.seek(3);
//2.2保存3 以后的所有数据到builder中 最后再插入
StringBuilder builder = new StringBuilder((int) new File("Hello.txt").length());
byte[] buffer = new byte[20];
int len;
while ((len = raf.read(buffer))!=-1){
builder.append(new String (buffer,0,len));
}
//调回指针,写入“xyz”
raf.seek(3);
raf.write("xyz".getBytes());
//将StringBuilder中的数据写入文件中
raf.write(builder.toString().getBytes());
System.out.println("插入成功!");
} catch (IOException e) {
e.printStackTrace();
} finally {
//3.
if (raf!=null){
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test是使用了Junit单元测试 大概就是一个不用main方法就可以运行的程序段
插入前:
插入后: