1

我正在尝试重命名之前用作 RandomAccessFile 的文件。

当我尝试重命名文件时,我在 renameTo 调用时收到错误消息。当我使用 Windows 应用程序进程监视器时,我看到没有重命名调用。

我怎么可能无法重命名作为 RandomAccessFile 打开的文件?

以下代码将复制我遇到的问题:

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

1 回答 1

1

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();
}
于 2014-12-09T20:41:17.643 回答