RandomAccessFile的使用_实现数据插入效果

package com.zhou.java;

import org.junit.Test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * RandomAccessFile 的使用
 * 1. RandomAccessFile 直接继承于 java.lang.Object 类,实现了 DataInput 和 DataOutput 接口
 * 2. RandomAccessFile 既可以作为一个输入流,又可以作为一个输出流
 *
 * 3.如果 RandomAccessFile 作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建
 *   如果写出到的文件存在,则会对原有文件进行覆盖(默认从头覆盖)
 *
 * 4.可以通过相关的操作,实现RandomAccessFile"插入"数据的效果
 *
 * @author upzhou
 * @create 2022-03-31 14:21
 */
public class RandomAccessFileTest {

    @Test
    public void test1() {

        RandomAccessFile raf1 = null;
        RandomAccessFile raf2 = null;
        try {
            raf1 = new RandomAccessFile(new File("小猫.jpg"),"r");
            raf2 = new RandomAccessFile(new File("小猫1.jpg"),"rw");

            byte[] buffer = new byte[1024];
            int len;
            while ((len = raf1.read(buffer)) != -1){
                raf2.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (raf1 != null){
                try {
                    raf1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (raf2 != null){
                    try {
                        raf2.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    @Test
    public void test2() throws IOException {

        RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw");

        raf1.seek(3);   //将指针调到角标为 3 的位置(从位置 3 开始覆盖)
        raf1.write("xyz".getBytes());

        raf1.close();
    }
    /*
    使用 RandomAccessFile 实现数据的插入效果
     */
    @Test
    public void test3() throws IOException {

        RandomAccessFile raf1 = new RandomAccessFile("hello.txt", "rw");

        raf1.seek(3);//将指针调到角标为 3 的位置(从位置 3 开始覆盖)
        //保存指针 3 后面的所有数据到 StringBuider 中
        StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());
        byte[] buffer = new byte[20];
        int len;
        while ((len = raf1.read(buffer)) != -1){
            builder.append(new String(buffer,0,len));
        }
        //调回指针,写入"xyz"
        raf1.seek(3);
        raf1.write("xyz".getBytes());
        //将 StringBuider 中写入文件中
        raf1.write(builder.toString().getBytes());

        raf1.close();
    }
}

 

posted @ 2022-04-30 15:01  UpZhou  阅读(46)  评论(0)    收藏  举报