Cannot delete temporary file after writing to it via a MappedByteBuffer

38 views Asked by At

When I run this JUnit test, it fails because file.delete() returns false:

@Test
public void testDeleteTempFile() throws Exception {
  File file = Files.createTempFile("_file_del_test", ".txt").toFile();
  try (RandomAccessFile f = new RandomAccessFile(file, "rw");
       FileChannel chan = f.getChannel()) {
    MappedByteBuffer buf = chan.map(
        FileChannel.MapMode.READ_WRITE, 0, 42);
    for (int i = 0; i < 42; i++) {
      buf.put((byte) 42);
    }
  }
  Assert.assertTrue(file.delete());
}

Why is this the case? I thought all resources are closed after the try block and there should be no reason that file.delete() fails.

0

There are 0 answers