JAVA_基础IO流随机存取文件流(四)

随机存取文件流

RandomAccessFile 声明在java.io包下,但直接继承于java.lang.Object类。并 且它实现了DataInputDataOutput这两个接口,也就意味着这个类可以作为输入流,也可以作为输出流。

构造器:public RandomAccessFile(File file, String mode)public RandomAccessFile(String name, String mode)
创建RandomAccessFile 类实例需要指定一个mode参数,该参数指定RandomAccessFile的访问模式:

r:以只读方式打开
rw:打开以便读取和写入
rwd:打开以便读取和写入;同步文件内容的更新
rws:打开以便读取和写入;同步文件内容和元数据的更新

public void test1() {
    RandomAccessFile randomAccessFile1 = null;
    RandomAccessFile randomAccessFile2 = null;
    try {
        randomAccessFile1 = new RandomAccessFile(new File("image.png"),"r");
        randomAccessFile2 = new RandomAccessFile(new File("image1.png"),"rw");
        byte[] buffer = new byte[1024];
        int len;
        while((len = randomAccessFile1.read(buffer)) != -1) {
            randomAccessFile2.write(buffer,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (randomAccessFile2 != null) {
            try {
                randomAccessFile2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (randomAccessFile1 != null) {
            try {
                randomAccessFile1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

如果RandomAccessFile作为输入流出现,写出到的文件不存在,则自动创建。如果文件存在,则对文本内容从头覆盖。

// hello.txt内容: 123456
public void test2() {
    RandomAccessFile rw = null;
    try {
        rw = new RandomAccessFile(new File("hello.txt"), "rw");
        rw.write("00".getBytes());// 003456
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (rw != null) rw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

RandomAccessFile 类也可以跳转文件任意位置进行读写。
void seek(long pos):将文件记录指针定位到 pos 位置。

//hello.txt内容:123456
public void test3() {
    RandomAccessFile rw = null;
    try {
        rw = new RandomAccessFile(new File("hello.txt"), "rw");
        rw.seek(3);// 将指针调到角标为3的位置
        rw.write("00".getBytes());// 123006
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (rw != null) rw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
posted @ 2021-01-06 21:39  TuoYingtao  阅读(79)  评论(0编辑  收藏  举报