I created a simple test that creates and deletes a file (the name does not change) in an infinite loop. The test runs for several seconds (sometimes more than 77,000 iterations!), And then with this exception:
Exception in thread "main" java.io.IOException: Access is denied at java.io.WinNTFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(Unknown Source) at DeleteTest.main(DeleteTest.java:11)
Here's the test logic:
final File f = new File(pathname); while (true) { final boolean create = f.createNewFile(); if (!create) { System.out.println("crate failed"); } else { final boolean delete = f.delete(); if (!delete) { System.out.println("delete failed"); } } }
How is this possible? The call is not interrupted. That will say. Therefore, deletion always succeeds, but createNewFile fails. This is what MSDN says about the win32 api DeleteFile :
The DeleteFile function marks a file for deletion when closing. Therefore, file deletion does not occur until the last file descriptor is closed. Subsequent calls to CreateFile to open the file fail ERROR_ACCESS_DENIED.
So, createNewFile does not close the file? The openjdk source tells us that the file is closed:
JNIEXPORT jboolean JNICALL Java_java_io_Win32FileSystem_createFileExclusively(JNIEnv *env, jclass cls, jstring pathname) { jboolean rv = JNI_FALSE; DWORD a; WITH_PLATFORM_STRING(env, pathname, path) { int orv; int error; JVM_NativePath((char *)path); orv = JVM_Open(path, JVM_O_RDWR | JVM_O_CREAT | JVM_O_EXCL, 0666); if (orv < 0) { if (orv != JVM_EEXIST) { error = GetLastError();
Can anyone explain this behavior?
source share