javajava-iorandomaccessfilemappedbytebuffer

Renaming file after it has been opened as a RandomAccessFile and mapped as a MappedByteBuffer


I am trying to rename a file that I used as a RandomAccessFile before.

When I try to rename the file I get an error on the renameTo call. When I use the Windows application Process Monitor I see that there was no rename call.

How is it possible that I cannot rename a file that was opened as a RandomAccessFile?

The following code will replicate the problem that I am having:

File f = new File("testfile.txt");

FileChannel fc = new RandomAccessFile(f, "rw").getChannel();
MappedByteBuffer mem = fc.map(FileChannel.MapMode.READ_WRITE, 0, 8);
mem.position(0);
fc.close();

File oldfile = new File("testfile.txt");
File newName = new File("testfile2.txt");
Boolean success = oldfile.renameTo(newName);
success = f.renameTo(newName);

Solution

  • The file is still open. You have to unmap the file from memory before you can rename it. You can find the solution here: How to unmap a file from memory mapped using FileChannel in java?

    For example (This method can be dangeraus):

    public static void unmap(MappedByteBuffer buffer)
    {
       sun.misc.Cleaner cleaner = ((DirectBuffer) buffer).cleaner();
       cleaner.clean();
    }