首页 > 编程笔记 > Java笔记 阅读:21

Java RandomAccessFile类的用法(附带实例)

在 Java 中,RandomAccessFile 类既不是输入流类的子类,也不是输出流类的子类。使用 RandomAccessFile 类可以实现以下两个目的:
RandomAccessFile 类常用的构造方法如下:
RandomAccessFile(File file,String mode)
RandomAccessFile(String name,String mode)
其中,mode 用来决定创建的流对文件的访问权利,可以是 r、rw、rws 或 rwd。其中,r 代表只读,rw 代表可读/写,rws 代表同步写入,rwd 代表将更新同步写入。

除了构造方法,RandomAccessFile 类还有如下两个核心的方法:
【实例】RandomAccessFile类的应用。
import java.io.RandomAccessFile;

public class Example {
    public static void main(String[] args) {
        RandomAccessFile randomf = null;
        try {
            randomf = new RandomAccessFile("D:\\3.txt", "rw");
            // 将若干数据写入文件中
            int[] data = new int[]{3, 8, 34, 333, 78, 21, 24, 43, 93, 555};
            for (int i = 0; i < data.length; i++) {
                // 在文件中写入一个数组元素
                randomf.writeInt(data[i]);
            }
            // 定位到第 4 个字节处
            randomf.seek(4);
            // 读取当前位置的数据
            System.out.println(randomf.readInt());
            // 隔一个读一个数据
            for (int i = 0; i < 10; i += 2) {
                randomf.seek(i * 4);
                System.out.print(randomf.readInt() + "\t");
            }
            System.out.println();
            // 在第 8 个字节的位置插入一个新的数据 38,替换之前的数据 34
            randomf.seek(8);
            randomf.writeInt(38);
            for (int i = 0; i < 10; i++) {
                randomf.seek(i * 4);
                // 输出文件中的每个数据
                System.out.print(randomf.readInt() + "\t");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (randomf != null) {
                    randomf.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
运行结果为:
8
3    34   78    24    93
3    8    38    333   78     21    24   43    93    555

相关文章