IO流19(完) --- RandomAccessFile实现数据的插入 --- 技术搬运工(尚硅谷)

时间:2021-10-19 01:13:29

原hello.txt文件中的内容:abcdefghijklmn

想要实现的效果是,将xyz插入到abc后面,将文件内容变成:abcxyzdefghijklmn

@Test
public void test18() throws IOException {
    File file = new File("hello.txt");
    RandomAccessFile raf = new RandomAccessFile(file, "rw");
    //将指针调到指针为3的位置,读取abc后面的内容,保存到builder中
    raf.seek(3);
    StringBuilder builder = new StringBuilder((int) file.length());
    byte[] buffer = new byte[20];
    int len;
    //此时只会读取指针为3及其后面的内容
    while ((len = raf.read(buffer)) != -1){
        builder.append(new String(buffer, 0, len));
    }

    //调回指针,写入“xyz”
    raf.seek(3);
    raf.write("xyz".getBytes());
    //指针此时已经自动移动到xyz后面。再写入复制的abc后面的内容
    raf.write(builder.toString().getBytes());
    
    raf.close();
}