Link to home
Start Free TrialLog in
Avatar of itailevitan
itailevitan

asked on

method File.delete() fails!!!

Hello dear programmers!

I'm trying to delete certain files. I've built a class with members:
File myFile;
File myDirFile;
the c'tor allocates myDirFile and sets it to point to the my requested directory.

Now, check out the following method in which method File.delete() always returns false. Do u know why?

public void removeAllCookies()
{
// "filesToRemove" will hold a list of
// file names of the files to be removed       
String[] filesToRemove = myTestDir.list();
for (int i=0; i<filesToRemove.length; i++)
 {
myFile = new File(filesToRemove[i]);
 if (myFile.delete() == true)
    System.out.println("File: " +  
    filesToRemove[i] + " has been
    removed.");
 else
    System.out.println("File: " +  
    filesToRemove[i] + " has not been
    removed.");
 }
}

filesToRemove holds what it should - so that part is fine. Debugging shows that
myFile.delete() always returns false.

If u can help please write your answer simply and with no "hints" that may seem obvious to u, for I am new in Java
(I'm a student).
Otherwise - Thank u 4 your time.
Avatar of andyhedges
andyhedges

Do the files actuall get deleted?
ASKER CERTIFIED SOLUTION
Avatar of sgoms
sgoms

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
sgoms,

It is better if u dont check if it's deleted or not,just delete it,thats been my experience.
Also sometimes files never get deleted ,I dunno why.
maybe it has got some lock on  it.

Always when u r deleting files from Java,if possible call System.gc() at end of ur code.

always keep all ur genarted files in a specific folder and try to delete those files everytime ur App is run.
mbormann,
point noted.i'll surelu\y keep this in mind nxt time i face a problem deleting files!
-sgoms
sgoms,
The reason I said to call a System.gc() is that when ur App is highly loaded then those files remain deleted in Memory but not from Hard disk,i.e their indexes r deleted.
so to flush out this we call a gc()

Regards
agreed
-sgoms
sgoms,
dont be so seriuos,Enjoy life man
:-)