Java技术篇·IO包·RandomAccessFile类
阅读原文时间:2021年04月20日阅读:1

有关知识及说明,全部在下边程序中体现。

package com.io;

import java.io.File;
import java.io.RandomAccessFile;

/**
 * RandomAccessFile Java提供的对文件内容的访问,既可以读也可以写。
 * 支持随机访问,可以访问任意位置。
 * java文件模型:在硬盘上是byte byte byte存储的,是数据的集合。
 * 打开文件:有两种模式 "rw"读写    "r"只读
 * 文件指针,打开文件时指针在开头pointer = 0;
 * 写方法:randomAccessFile.write(int)---->只写一个字节(后8位),同时指针指向下一个字节的位置,准备再次写入。
 * 读方法:int b = randomAccessFile.read()---->读一个字节
 * 文件读写完成之后一定要关闭(否则报Oracle官方说明错误)
 */
public class RandomAccessFileTest {

    public static void main(String[] args) throws Exception {
        String str = "中国CJL";

        File file = new File("/Users/cjl/Downloads/io_test/random_file1.txt");
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");

        byte[] bytes = str.getBytes("gbk");
        randomAccessFile.write(bytes);

        System.out.println("当前指针位置:" + randomAccessFile.getFilePointer());

        //读操作,将文件内容读取到字节数组中
        randomAccessFile.seek(0);
        byte[] readBytes = new byte[(int) randomAccessFile.length()];
        //可以一次只读一个字节,也可以全部一次性读取到字节数组,读入到字节数组也可以跟起始和结束位置
        randomAccessFile.read(readBytes);

        //以16进制编码的形式输出,一个byte为8位,可用两个十六进制位表示
        for (byte b : readBytes) {
            System.out.print(Integer.toHexString(b & 0xff) + " ");
        }
        System.out.println();

        //转换成字符输出,不指定编码的情况下,结果位乱码
        String result = new String(readBytes);
        System.out.println("读取结果:" + result);

        //转换成字符输出,以什么编码存储,就以什么编码读取
        String result2 = new String(readBytes, "gbk");
        System.out.println("读取结果:" + result2);

        randomAccessFile.close();
    }
}
/*
* 输出
* 当前指针位置:7
* d6 d0 b9 fa 43 4a 4c
* 读取结果:�й�CJL
* 读取结果:中国CJL
* */

输出文件内容: