用到NIO的相关类--MappedByteBuffer时的一个BUG。
例如:
public void testMappedByteBufferRead() {
int length = 10485760;
MappedByteBuffer out = null;
RandomAccessFile ranFile = null;
File file = null;
try {
file = new File("d:/test.txt");
ranFile = new RandomAccessFile(file, "rw");
out = ranFile.getChannel().map(
FileChannel.MapMode.READ_WRITE, 0, length);
for (int i = 0; i < length; i++)
out.put((byte) 'x');
System.out.println("Finished writing");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
file.delete();
System.out.println("Delete File");
Thread.sleep(100000);
} catch (Exception e) {
e.printStackTrace();
}
}
int length = 10485760;
MappedByteBuffer out = null;
RandomAccessFile ranFile = null;
File file = null;
try {
file = new File("d:/test.txt");
ranFile = new RandomAccessFile(file, "rw");
out = ranFile.getChannel().map(
FileChannel.MapMode.READ_WRITE, 0, length);
for (int i = 0; i < length; i++)
out.put((byte) 'x');
System.out.println("Finished writing");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
file.delete();
System.out.println("Delete File");
Thread.sleep(100000);
} catch (Exception e) {
e.printStackTrace();
}
}
在网上收集一些资料都说是JAVA的一个BUG,一些网友自己写out的close()函数:
public static void clean(final Object buffer) throws Exception {
AccessController.doPrivileged(new PrivilegedAction() {
public Object 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;
}
});
}
但调用此函数后依然无法删除文件,即out没有关闭。
此问题比较棘手,不知各位技术牛人是否有更好的方法,望赐教,谢谢。