使用FileChannel 处理文件时,文件无法删除

本文解决了在Windows环境下使用Java的FileChannel map方法后无法删除文件的问题。通过手动调用unmap方法,可以有效地释放资源,允许文件被删除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Windows上使用FileChannel的map方法之后, 不能够删除掉文件。

in = new FileInputStream(file);
ch = in.getChannel();
ByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
String md5 = MD5(byteBuffer);
ch.close();
in.close();

Oracle的buglist上看到了这个问题的描述. 

引用


We cannot fix this.  Windows does not allow a mapped file to be deleted.  This 
problem should be ameliorated somewhat once we fix our garbage collectors to 
deallocate direct buffers more promptly (see 4469299), but otherwise there's 
nothing we can do about this. 


sun.misc.Cleaner为我们干了关闭文件, 释放资源的脏活. 这个类是一个幻引用, 所以会在gc的时候调用到. FileChannel正是调用了这个Cleaner, 在gc的时候做unmap. 

解决:

in = new FileInputStream(file);
ch = in.getChannel();
ByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
String md5 = MD5(byteBuffer);

Method method = FileChannelImpl.class.getDeclaredMethod("unmap", MappedByteBuffer.class);
method.setAccessible(true);
method.invoke(FileChannelImpl.class, byteBuffer);
ch.close();
in.close();

手动调unmap, 应该就可以在windows上释放掉资源了。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值