RandomAccessFile随机访问流

RandomAccessFile:

  RandomAccessFile既可以读取文件内容,也可以向文件输出数据。

  同时,RandomAccessFile支持“随机访问”的方式,程序快可以直接跳转到文件的任意地方来读写数据

 

  使用场景:

  ①、由于RandomAccessFile可以自由访问文件的任意位置,所以如果需要访问文件的部分内容,而不是把文件从头读到尾,使用RandomAccessFile将是更好的选择

  ②、与OutputStream、Writer等输出流不同的是,RandomAccessFile允许自由定义文件记录指针,RandomAccessFile可以不从开始的地方开始输出,因此RandomAccessFile可以向已存在的文件后追加内容。如果程序需要向已存在的文件后追加内容,则应该使用RandomAccessFile

 

    

 

  构造函数:

    public RandomAccessFile(File file, String mode)

  file参数来制定文件

  mode参数指定RandomAccessFile的访问模式,一共有4种模式:

    **"r" : ** 以只读方式打开。调用结果对象的任何 write 方法都将导致抛出 IOException

    "rw": 打开以便读取和写入

    "rws": 打开以便读取和写入。相对于 "rw","rws" 还要求对“文件的内容”或“元数据”的每个更新都同步写入到基础存储设备

    "rwd" : 打开以便读取和写入,相对于 "rw","rwd" 还要求对“文件的内容”的每个更新都同步写入到基础存储设备

 

  RandomAccessFile类包含了一个记录指针,用以标识当前读写处的位置,当程序新创建一个RandomAccessFile对象时,该对象的文件记录指针位于文件头(也就是0处),当读/写了n个字节后,文件记录指针将会向后移动n个字节。

  除此之外,RandomAccessFile可以自由的移动记录指针,即可以向前移动,也可以向后移动。RandomAccessFile包含了以下两个方法来操作文件的记录指针.

    long getFilePointer(); 返回文件记录指针的当前位置

    void seek(long pos); 将文件记录指针定位到pos位置

    

  使用示例:

  ①:指定位置读取文件

public static void main(String[] args) {
    RandomAccessFile accessFile = null;
    try {
        File file = new File(filePath);
        accessFile = new RandomAccessFile(file, "r");

        // 获取 RandomAccessFile对象文件指针的位置,初始位置为0
        log.debug("输入内容:{}", accessFile.getFilePointer());

        // 移动文件记录指针的位置
        accessFile.seek(1000);

        byte[] b = new byte[1024];
        int hasRead = 0;
        //循环读取文件
        while ((hasRead = accessFile.read(b)) > 0) {
            //输出文件读取的内容
            System.out.print(new String(b, 0, hasRead));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        accessFile.close();
    }
}

  ②:向文件中追加内容

public static void main(String[] args) {
    RandomAccessFile accessFile = null;
    File file = null;
    try {
        file = new File(filePath);
        // 以读写的方式打开一个RandomAccessFile对象
        accessFile = new RandomAccessFile(file, "rw");

        //将记录指针移动到该文件的最后
        accessFile.seek(accessFile.length());

        //向文件末尾追加内容
        accessFile.writeChars("这是追加内容。。");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        accessFile.close();
    }
}

  ③:向文件制定位置插入内容

/**
 * 向文件指定位置插入内容
 *
 * @param filePath     源文件路径
 * @param pos          插入文件指定位置
 * @param writeContent 写入内容
 */
private static void readFileThenWrite(String filePath, long pos, String writeContent) throws IOException {
    RandomAccessFile raf = null;
    File tempFile = File.createTempFile("tmp", null);
    tempFile.deleteOnExit();
    try {
        // 以读写的方式打开一个RandomAccessFile对象
        raf = new RandomAccessFile(new File(filePath), "rw");

        // 创建一个临时文件来保存插入点后的数据
        FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
        FileInputStream fileInputStream = new FileInputStream(tempFile);

        // 把文件记录指针定位到pos位置
        raf.seek(pos);
        raf.seek(pos);

        //------------将插入点后的内容读入临时文件中保存------------
        byte[] bytes = new byte[64];
        //用于保存实际读取的字节数据
        int hasRead = 0;
        //使用循环读取插入点后的数据
        while ((hasRead = raf.read(bytes)) != -1) {
            //将读取的内容写入临时文件
            fileOutputStream.write(bytes, 0, hasRead);
        }

        //------------用于插入内容 ------------
        //把文件记录指针重新定位到pos位置
        raf.seek(pos);

        //追加需要插入的内容
        raf.write(writeContent.getBytes());

        //追加临时文件中的内容
        while ((hasRead = fileInputStream.read(bytes)) != -1) {
            //将读取的内容写入临时文件
            raf.write(bytes, 0, hasRead);
        }
    } catch (Exception e) {
        throw e;
    }
}

 

 

END.

posted @ 2022-08-31 19:23  杨岂  阅读(82)  评论(0编辑  收藏  举报