文件在使用FileChannel.map后不能被删除(Windows上)

 同事发现在Windows上使用FileChannel的map方法之后, 不能够删除掉文件. 我在Linux上试了一下, 发现没这个问题。 做个笔记, 记录一下.

Java代码 复制代码 收藏代码
  1. import java.io.File;
  2. import java.io.RandomAccessFile;
  3. import java.lang.reflect.Method;
  4. import java.nio.ByteBuffer;
  5. import java.nio.MappedByteBuffer;
  6. import java.nio.channels.FileChannel;
  7. import java.nio.channels.FileChannel.MapMode;
  8.  
  9. import sun.nio.ch.FileChannelImpl;
  10.  
  11. public class TestDeleteMappedFile {
  12.  
  13. public static void main(String args[]) {
  14. File f = new File("mapfile");
  15. RandomAccessFile aFile = null;
  16. FileChannel inChannel = null;
  17. try {
  18. aFile = new RandomAccessFile(f, "rw");
  19. inChannel = aFile.getChannel();
  20. ByteBuffer buf = inChannel.map(MapMode.READ_WRITE, 0L, 4);
  21. } catch (Exception e) {
  22. e.printStackTrace();
  23. } finally {
  24. try {
  25. inChannel.close();
  26. aFile.close();
  27. } catch (Exception e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. System.out.println("delete " + f + " : " + f.delete());
  32. }
  33. }
import java.io.File;
import java.io.RandomAccessFile;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
 
import sun.nio.ch.FileChannelImpl;
 
public class TestDeleteMappedFile {

  public static void main(String args[]) {
    File f = new File("mapfile");
    RandomAccessFile aFile = null;
    FileChannel inChannel = null;
    try {
      aFile = new RandomAccessFile(f, "rw");
      inChannel = aFile.getChannel();
      ByteBuffer buf = inChannel.map(MapMode.READ_WRITE, 0L, 4);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        inChannel.close();
        aFile.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    System.out.println("delete " + f + " : " + f.delete());
  }
}

 

你可能感兴趣的:(windows)