gpt4 book ai didi

java - randomAccessFile 方法不写入或读取整数?

转载 作者:行者123 更新时间:2023-12-02 02:56:28 29 4
gpt4 key购买 nike

我有两种方法,一种将 10 个整数写入 randomAccessFile,另一种读取这 10 个整数。我相信 writer 方法没有按预期运行。

这是我写入随机文件的方法:

try{
RandomAccessFile file = new RandomAccessFile(nextPath, "rw");
System.out.println("Writing these ints to file");
file.seek(0);
// here I loop 10 times and write the int at position i
for (int i = 0; i < 10; i++)
{
file.seek(i);
toAdd = randInt(1,10);
file.writeInt(toAdd);
System.out.printf(toAdd + " ");

}
file.seek(0);
System.out.println("");
}catch(IOException ex){
System.out.println("Error");
System.exit(0);}

这是我读取整数的方法:

public int[] readRandom()
{
System.out.println("Unsorted ints found in random file:");
int[] randomInts = new int[10];
try{
RandomAccessFile file = new RandomAccessFile(nextPath, "rw");
file.seek(0);
// here I loop 10 times, and read the Int at position i
for(int i = 0; i < 10; i++)
{
file.seek(i);
randomInts[i] = file.readInt();
System.out.printf(randomInts[i] + " ");


}
file.seek(0);
System.out.println("");
}catch(IOException exc){
System.out.println("Error reading ints");
System.exit(0);}
return randomInts;
}

这是我的输出:为什么只读取最后一个 int?

Writing these ints to file
1 4 5 6 2 4 10 6 5 5
Unsorted ints found in random file:
0 0 0 0 0 0 0 0 0 5

最佳答案

为什么使用RandomAccessFile来执行顺序写入和顺序读取?它违背了此类的目的。
此外,您不应该震惊捕获的异常,而应该记录或跟踪它们。

关于您的意外结果,它是由不需要的 seek() 调用引起的。您无需在每次读取或写入操作时调用 seek(),因为 readInt()writeInt() 会使光标向前移动.

我简化了您的示例代码以强调重要部分:

public void write() {
try {
RandomAccessFile file = new RandomAccessFile("temp.txt", "rw");
System.out.println("Writing these ints to file");
file.seek(0);
for (int i = 0; i < 10; i++) {
file.writeInt(i);
System.out.printf(i + " ");
}
} catch (IOException ex) {
ex.printStackTrace();
System.exit(0);
}
}

public int[] readRandom() {
System.out.println("Unsorted ints found in random file:");
int[] randomInts = new int[10];
try {
RandomAccessFile file = new RandomAccessFile("temp.txt", "rw");
long filePointer = file.getFilePointer();

file.seek(0);
for (int i=0; i<10; i++){
randomInts[i] = file.readInt();
System.out.printf(randomInts[i] + " ");
}
} catch (IOException ex) {
ex.printStackTrace();
System.exit(0);
}
return randomInts;
}

关于java - randomAccessFile 方法不写入或读取整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42986143/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com