gpt4 book ai didi

java - 如何正确关闭 MappedByteBuffer?

转载 作者:搜寻专家 更新时间:2023-11-01 01:52:03 25 4
gpt4 key购买 nike

这是我正在运行的代码:

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
public static void main(String[] args) throws Exception {
String filePath = "D:/temp/file";
RandomAccessFile file = new RandomAccessFile(filePath, "rw");

try {
MappedByteBuffer buffer = file.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, 128);

// Do something
buffer.putInt(4);
} finally {
file.close();
System.out.println("File closed");
}

System.out.println("Press any key...");
System.in.read();

System.out.println("Finished");
}
}

在按下某个键之前,我试图在 FAR 管理器中手动删除该文件。但是 FAR 说文件被锁定了:

 The process cannot access the file because it is being used by another process.
Cannot delete the file
D:\temp\file
Object is being opened in:
Java(TM) Platform SE binary (PID: 5768, C:\Program Files\Java\jdk1.8.0_05\bin\javaw.exe)

只有按下一个键,应用程序才会终止,我才能删除文件。

我的代码有什么问题?

最佳答案

试试这个。

public class Test
{
public static void main(String[] args) throws Exception {
String filePath = "D:/temp/file";
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
FileChannel chan = file.getChannel();
try {
MappedByteBuffer buffer = chan.map(FileChannel.MapMode.READ_WRITE, 0, 128);

// Do something
buffer.putInt(4);
buffer.force();
Cleaner cleaner = ((sun.nio.ch.DirectBuffer) buffer).cleaner();
if (cleaner != null) {
cleaner.clean();
}
} finally {
chan.close();
file.close();
System.out.println("File closed");
}

System.out.println("Press any key...");
System.in.read();

System.out.println("Finished");
}
}

关于java - 如何正确关闭 MappedByteBuffer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25238110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com