C
contrex
I have a simple question about deleting a file:
Why it isn't deleted immediatly?
There are neither other processes nor threads which access the file
nor any security issues!
Here is my test code:
public void deleteFile(File f) {
if (f!=null && f.exists()) {
f.delete();
System.out.println("DELETED!!");
}
for(int x=0; x<A_BIGNUMBER && f!=null && f.exists(); x++) {
f.delete();
System.out.println("DELETE NR." + x);
}
}
And the output varies. Sometimes is it:
DELETED!!
Sometimes is it:
DELETED!!
DELETE NR.0
DELETE NR.1
DELETE NR.2
DELETE NR.3
....
DELETE NR.464
Yes! 464 tries in order to delete a file!!
So I thought I have to run the garbage collector if the file persists
and I wrote:
public static void deleteFile(File f) {
if (f!=null && f.exists()) {
f.delete();
System.out.println("DELETED!!");
}
if (f!=null && f.exists()) {
System.gc();
f.delete();
System.out.println("SECOND DELETED!!");
}
}
And the file is really deleted at last at the second try (I hope so, I
tried it only some times).
Is this "good design"?
How do you delete a file correctly immediatly?
Thanks in advance!
Why it isn't deleted immediatly?
There are neither other processes nor threads which access the file
nor any security issues!
Here is my test code:
public void deleteFile(File f) {
if (f!=null && f.exists()) {
f.delete();
System.out.println("DELETED!!");
}
for(int x=0; x<A_BIGNUMBER && f!=null && f.exists(); x++) {
f.delete();
System.out.println("DELETE NR." + x);
}
}
And the output varies. Sometimes is it:
DELETED!!
Sometimes is it:
DELETED!!
DELETE NR.0
DELETE NR.1
DELETE NR.2
DELETE NR.3
....
DELETE NR.464
Yes! 464 tries in order to delete a file!!
So I thought I have to run the garbage collector if the file persists
and I wrote:
public static void deleteFile(File f) {
if (f!=null && f.exists()) {
f.delete();
System.out.println("DELETED!!");
}
if (f!=null && f.exists()) {
System.gc();
f.delete();
System.out.println("SECOND DELETED!!");
}
}
And the file is really deleted at last at the second try (I hope so, I
tried it only some times).
Is this "good design"?
How do you delete a file correctly immediatly?
Thanks in advance!