I am trying to understand the following behavior. My older code,
String path = "C:/temp/sample.txt";
String mode= "rw";
FileChannel channel = new RandomAccessFile(path, mode).getChannel();
// some code to write to this file
// finally delete
File file = new File(path);
boolean isDeleted = file.delete();
System.out.println("Is Deleted - " + isDeleted);
O/P - Is Deleted - false
Only if i do a "channel.close();" before i delete the file. Does it delete the file and return true.
Newer replaced code,
String path = "C:/temp/sample.txt";
FileChannel fChannel = FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
// some code to write to this file
// finally delete
File file = new File(path);
boolean isDeleted = file.delete();
System.out.println("Is Deleted - " + isDeleted);
O/P - Is Deleted - true
But this does not delete the file until the application exits. If i use "fChannel.close()", it will delete it immediately.
Few questions,
- Why different behaviors, i understand both are different types, i.e. RA vs Seekable Channel. But not sure, why delete should behave differently.
- In the newer implementation, if it does not delete the file until, the application exits, then it should either return false (i.e. will not delete, until close is called) or then delete immediately.
I don't know if i have hit a bug or missing something. Any pointers can help.
Thanks
From the specification of
RandomAccessFile.getChannel():In other words, the returned channel and the
RandomAccessFilemaintain a bidirectional relationship and both are either open or closed. So in this regard, it’s not theFileChannelbut theRandomAccessFile, which is still open while the channel is open, that keeps theFilelocked.When you call
closeon such aFileChannelit will close the associatedRandomAccessFileas well, letting nothing remain within the JRE preventing thedeleteoperation.In contrast, when creating a
FileChannelviaFileChannel.openit doesn’t have an associatedFileInputStream,FileOutputStream, norRandomAccessFileand doesn’t prevent aFile.deleteoperation.So when there is nothing within the JVM/JRE preventing the
deleteoperation, it will exhibit the behavior of the underlying operating system, e.g. onMicrosoft Windows:This is exactly the observed behavior. You don’t need to exit the JVM, closing the
FileChannelis enough to complete the deletion.