注意你这句代码:
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0,channel.size()); 这句代码通道建立了map映射,你在file.delete();这句代码的前面,仅仅把buffer 给 clear了
Clears this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded. 此时并没有解除映射,所以你在删除之前还要把映射解除:
public static void unmap(final Object buffer) {
AccessController.doPrivileged(new PrivilegedAction(){
@Override
public T run() {
try {
Method getCleanerMethod = buffer.getClass().getMethod("cleaner", new Class[0]);
getCleanerMethod.setAccessible(true);
sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod.invoke(buffer, new Object[0]);
cleaner.clean();
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
});
} 最终是:
unmap(buf);
file.delete()
这样就可以删除了,你试试。