关于MappedByteBuffer使用后无法删除问题

来源:互联网 发布:edf调度算法源代码 编辑:程序博客网 时间:2024/06/06 16:30

网上已经提供了些方法,我只是为了做个备份资料 . . .


以下就是我测试用的代码了

import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.lang.reflect.Method;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;import java.security.AccessController;import java.security.PrivilegedAction;import org.junit.Assert;import org.junit.Before;import org.junit.Test;public class TestMappedByteBuffer {File file;MappedByteBuffer buff;/** * initialization process * * @throws Exception */@Beforepublic void init() throws Exception {file = new File("/tmp/test.txt");if (!file.exists()) {file.createNewFile();}FileOutputStream out = new FileOutputStream(file);out.write("TEST\nTEST".getBytes());out.close();}/** * delete file method * * @throws Exception */@Testpublic void deleteFile() throws Exception {mappedFile();cleanHandle(buff);file.delete();// check existsAssert.assertEquals(false, file.exists());}/** * Mapped file * * @throws Exception */public void mappedFile() throws Exception {FileChannel channel = new FileInputStream(file).getChannel();buff = channel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());channel.close();}/** * clean handle method * * @param obj *            process object */public void cleanHandle(final Object obj) {// validate method parameterif (obj == null) {return;}AccessController.doPrivileged(new PrivilegedAction<Object>() {public Object run() {try {Method cleaner = obj.getClass().getMethod("cleaner",new Class[0]);if (cleaner != null) {cleaner.setAccessible(true);// 1.method((sun.misc.Cleaner) cleaner.invoke(obj, new Object[0])).clean();// 2.method/*Object __obj = cleaner.invoke(obj, new Object[0]);Method clean = __obj.getClass().getMethod("clean",new Class[0]);if (clean != null) {clean.invoke(__obj, new Object[0]);}*/}} catch (Exception e) {e.printStackTrace();}return null;}});}}


0 0
原创粉丝点击