Question

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.)

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top