mark1092 mark1092 -4 years ago 85
Java Question

randomAccessFile method not writing or reading ints?

I have two methods, one to write 10 ints to a randomAccessFile and one to read the 10 ints. I believe the writer method is not functioning as intended.

Here is my method to write to random file:

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);}


Here is my method to read the ints:

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;
}


Here is my output: Why is only the last int being read?

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

Answer Source

You have missed an important point when you are doing file.seek(i). The seek() method seeks for the byte location you provide and you are incrementing the position to seek by 1. But when you write integers to file it writes 4 bytes for every integers. Your counter should be like this

for (int i = 0; i < 10; i++) {
    file.seek(i*4);
    toAdd = randInt(1,10);
    file.writeInt(toAdd); 
    System.out.printf(toAdd + " ");
 }

And obviously for the read you do this

for (int i = 0; i < 10; i++)
{
    file.seek(i*4);
    randomInts[i] = file.readInt();
    System.out.printf(randomInts[i] + " ");

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download