首页 > 解决方案 > RandAccessFile 中的 seek(0) 方法删除我的内容

问题描述

在这个项目中,我想将每个新数字放在随机访问文件的开头。但是 seek() 方法会删除文件中的所有其他数字。我不知道为什么。

package first;

import java.io.*;

public class Demo {
    public static void main(String[] args) throws IOException, InterruptedException {

        File file = new File("test.dat");
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        raf.setLength(0);
        for (int i = 0; i < 10; i++) {
            raf.writeInt(i);
            raf.seek(0);//setting the pointer to the beginning of the file
        }

        //printing the numbers
        System.out.println(raf.length());
        for (int i = 0; i < 10; i++) {
            raf.seek(i * 4);
            System.out.println(raf.readInt());

        }

    }

}

因此控制台输出是

Exception in thread "main" java.io.EOFException
    at java.base/java.io.RandomAccessFile.readInt(RandomAccessFile.java:846)
    at liangweb/chapter37.Demo.main(Demo.java:20)
4
9


标签: javarandomaccessfile

解决方案


推荐阅读