我有兩種方法,一種是將10個整數寫入randomAccessFile,另一個是讀取10個整數。我相信作家的方法沒有按預期運作。randomAccessFile方法沒有寫入或讀取整數?
這裏是我的方法寫入隨機文件:
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
這解決了這個問題。所以如果我要寫雙打而不是整數,我會乘以8? – mark1092
答案是肯定的。你可以檢查RandomAccessFile的[specification](https://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html) – mesbah