如何从java中使用FileChannel映射的内存中取消映射文件? [英] How to unmap a file from memory mapped using FileChannel in java?

查看:184
本文介绍了如何从java中使用FileChannel映射的内存中取消映射文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 FileChannel.map()将文件(sample.txt)映射到内存,然后使用 fc关闭频道。关闭()。在此之后,当我使用FileOutputStream写入文件时,我收到以下错误:

I am mapping a file("sample.txt") to memory using FileChannel.map() and then closing the channel using fc.close(). After this when I write to the file using FileOutputStream, I am getting the following error:


java.io.FileNotFoundException:
sample.txt(请求的操作
不能在打开
用户映射部分的文件上形成)

java.io.FileNotFoundException: sample.txt (The requested operation cannot be per formed on a file with a user-mapped section open)



File f = new File("sample.txt");
RandomAccessFile raf = new RandomAccessFile(f,"rw");
FileChannel fc = raf.getChannel();
MappedByteBuffer mbf = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
fc.close();
raf.close();

FileOutputStream fos = new FileOutputStream(f);
fos.write(str.getBytes());
fos.close();

我认为这可能是由于文件仍然映射到内存,即使我关闭 FileChannel 。我对吗?。如果是这样,我如何从内存中取消映射文件?(我在API中找不到任何方法)。
谢谢。

I presume this may be due to file being still mapped to the memory even after I close the FileChannel. Am I right?. If so, how can I "unmap" the file from memory?(I can't find any methods for this in the API). Thanks.

编辑:
看起来它(添加一个unmap方法)作为RFE提交给sun一段时间了:
http://bugs.sun.com/view_bug.do?bug_id=4724038

推荐答案

来自 MappedByteBuffer javadoc:

From the MappedByteBuffer javadoc:


映射的字节缓冲区及其表示的文件映射在缓冲区本身被垃圾收集之前保持有效。

A mapped byte buffer and the file mapping that it represents remain valid until the buffer itself is garbage-collected.

尝试调用 System.gc()?即使这只是对VM的建议。

Try calling System.gc()? Even that's only a suggestion to the VM.

这篇关于如何从java中使用FileChannel映射的内存中取消映射文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆