0

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

user141444
  • 53
  • 1
  • 3

1 Answers1

4

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
  • 3,583
  • 4
  • 25
  • 32
  • 1
    @Martin OConnor: You should also check for nullness on raf.close(), to be sure. – akarnokd Jul 31 '09 at 16:11
  • Thank you, still not used to file i/o in java. – user141444 Jul 31 '09 at 17:49
  • Or use try-with-resources like this: `try (RandomAccessFile raf = new RandomAccessFile(f)) { // do stuff }` however that is not going to work when using MappedByteBuffer, see https://stackoverflow.com/questions/25238110/how-to-properly-close-mappedbytebuffer – Vlad May 24 '22 at 13:27
  • At the time the question was asked, the latest Java was Java SE 6, so try-with-resources was not available – Martin OConnor May 30 '22 at 19:07