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