views:

49

answers:

1

I'm working on a project where I'm using RandomAccessFile. The biggest issue I am having is that even though I close the file after it being accessed the file does not close until the entire application exits. Is this standard behavior or does anyone have some idea what's going on? The code basically looks like:

RandomAccessFile raf = new RandomAccessFile(f);
//do stuff
raf.close();

Both sections where I am using a RandomAccessFile are like this (i.e. I am 100% sure that I am calling close on the files.)

+4  A: 

You want to make sure that your close is inside a finally block like this

RandomAccesFile raf = null;
try {
    raf = new RandomAccessFile(f);
    //do stuff
} finally {
   if (raf != null) {
      raf.close();
   }
}

Otherwise an exception can cause close() never to be executed.

Martin OConnor
@Martin OConnor: You should also check for nullness on raf.close(), to be sure.
kd304
@kd304 Of course, you are right :)
Martin OConnor
Thank you, still not used to file i/o in java.