java - 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
解决方案
推荐阅读
- python - 是否有更好的方法可以根据输入在函数中选择不同的操作?
- c++ - 通过 ofstream 输出到文件时提升序列化“读取访问冲突”
- docker - 从本地 GitLab 运行程序执行时,如何将构建标志包含到 docker?
- c - 在 C99 的 for 循环体之外声明计数器有什么好处吗?
- c# - 使用 xunit 和 .net core 3.1 进行单元测试时退出记录器
- compiler-errors - 在我第一次尝试时编译 clojurescript 时出错
- hadoop - -Dmapred.job.name 不适用于 s3-dist-cp 命令
- mysql - 无法将特定表中的任何数据插入我的数据库 MySQL
- javascript - 我怎样才能转换这个对象
- javascript - 在 Vuex 存储状态更改时更新 DOM