【问题标题】:Renaming file after it has been opened as a RandomAccessFile and mapped as a MappedByteBuffer在文件作为 RandomAccessFile 打开并映射为 MappedByteBuffer 后重命名文件
【发布时间】:2023-03-19 14:38:01
【问题描述】:

我正在尝试重命名以前用作 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);

【问题讨论】:

  • 是因为文件仍然打开(我看到你关闭了)?在 Microsoft 的 Windows 上,您无法重命名打开的文件。
  • 我刚刚注意到您将它重命名了两次,这很重要。 (“测试文件测试文件……”)

标签: java java-io randomaccessfile mappedbytebuffer


【解决方案1】:

文件仍处于打开状态。您必须先从内存中取消映射文件,然后才能重命名它。您可以在这里找到解决方案:How to unmap a file from memory mapped using FileChannel in java?

例如(这种方法可能很危险):

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

【讨论】:

    猜你喜欢
    • 2012-07-08
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    相关资源
    最近更新 更多