在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上释放掉资源了。