0
点赞
收藏
分享

微信扫一扫

Java IO RandomAccessFile

正义的杰克船长 2022-03-15 阅读 36

⭐写在前面⭐

文章目录

Java IO RandomAccessFile

RandomAccessFile

构造函数

public RandomAccessFile(String name, String mode)
public RandomAccessFile(File file, String mode)

RandomAccessFile构造函数有两个参数,其中第一个参数都是表示文件路径或者File实例。第二个参数指定的是mode,该参数是用来指定RandomAccessFile的访问模式,有 4 种值

  • “r” 以只读方式来打开指定文件夹。如果试图对该RandomAccessFile执行写入方法,都将抛出IOException异常。
  • “rw” 以读,写方式打开指定文件。如果该文件尚不存在,则试图创建该文件。
  • “rws” 以读,写方式打开指定文件。相对于”rw” 模式,还要求对文件内容或元数据的每个更新都同步写入到底层设备。
  • “rwd” 以读,写方式打开指定文件。相对于”rw”模式,还要求对文件内容每个更新都同步写入到底层设备。

特殊的方法

long getFilePointer();
void seek(long pos);

从指定位置读取文件

读取电脑磁盘上 letter.txt 文件,从文件中第3个字符开始读取,文件路径: e:\Java\letter.txt
在这里插入图片描述
代码示例:

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

public class RandomAccessFileTest01 {
    public static void main(String[] args) {
        String pathFile = "e:\\Java\\letter.txt";
        RandomAccessFile randomAccessFile = null;

        try {
            randomAccessFile = new RandomAccessFile(pathFile, "r"); // r 只读模式
            //移动文件记录指针的位置
            randomAccessFile.seek(3);

            byte[] bytes = new byte[4];
            int readLength = 0;

            while ((readLength = randomAccessFile.read(bytes)) != -1) {
                System.out.print(new String(bytes,0,readLength));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {//关闭流
            try {
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

运行结果:
在这里插入图片描述
🚀解读:
代码示例中以 只读模式 创建了RandomAccessFile对象,此时只能读取文件内容,而不能写入。又因为调用了seek(3)方法,把文件指针的偏移量移动到3的位置,也就是从3字节开始读取数据。
在这里插入图片描述

向文件中追加内容

向电脑磁盘上 letter.txt 文件的末尾追加“Java”内容,文件路径: e:\Java\letter.txt
在这里插入图片描述
代码示例:

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

public class RandomAccessFileTest02 {
    public static void main(String[] args) {
        String pathFile = "e:\\Java\\letter.txt";

        RandomAccessFile randomAccessFile = null;

        try {
            randomAccessFile = new RandomAccessFile(pathFile,"rw");
            long length = randomAccessFile.length();
            randomAccessFile.seek(length);//将文件指针偏移量移动到最后
            randomAccessFile.write("Java".getBytes());//写进数据
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {//关闭流
            try {
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

运行结果:
在这里插入图片描述

向文件指定位置插入内容

向电脑磁盘上 letter.txt 文件中字母c后追加“Java”内容,文件路径: e:\Java\letter.txt。因为直接插入会把字母c后的内容覆盖,所以我们先把字母c后的内容读取出来保存在一个临时文件中,待内容追加完成后,再次把临时文件中的内容写入原文件后。
在这里插入图片描述
代码示例:

import java.io.*;

public class RandomAccessFileTest {
    public static void main(String[] args) throws IOException {
        String path = "e:\\Java\\letter.txt";
        int index = 3;
        String content = "Java";
        appendContent(path,index,content);
    }

    /**
     * 往文件中指定位置写入内容
     * @param path :指定文件
     * @param index :指定文件中位置
     * @param content :追加的内容
     */
    public static void appendContent(String path,Integer index, String content) {
        File file = new File(path);
        if (!file.exists()) {
            System.out.println("文件不存在");
            return;
        }

        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file,"rws");//创建读写模式创建RandomAccessFile对象

            //检验插入位置合法性
            if (index > raf.length()) {
                System.out.println("插入位置越界");
                return;
            }

            //创建临时文件
            File tempFile = File.createTempFile("temp", null);

            //程序退出时删除临时文件
            tempFile.deleteOnExit();

            RandomAccessFile tempRaf = new RandomAccessFile(tempFile,"rw");

            //移动指针偏移量到指定位置
            raf.seek(index);

            //把原文件index后的内容读取出来存储到临时文件中
            byte[] bytes = new byte[100];
            int readLen = 0;
            while((readLen = raf.read(bytes)) != -1) {
                tempRaf.write(bytes,0,readLen);
            }

            //让文件指针再次移动到指定位置
            raf.seek(index);

            //将追加内容写入
            raf.write(content.getBytes());

            //移动临时文件中的指针偏移量到0
            tempRaf.seek(0);

            //将临时文件中的内容写入原文件
            while((readLen = tempRaf.read(bytes)) != -1) {
                raf.write(bytes,0,readLen);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {//关闭流
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

运行结果:
在这里插入图片描述

举报

相关推荐

0 条评论