Wednesday, May 14, 2008

Power of Java, In deleting the files that Windows cannot

Today, in one of the programs, I messed up a little piece of code that creates a folder in another, which ended up creating folders in an infinite loop. The folder name was ae, but there were so many of them ae in ae in ae .... Then I just wanted to clear the folder and start afresh with the fixed code. But guess what. Windows would not delete the folder because the name is too long. This was the exact error..

"cannot delete the file name you specified is not valid or too long"

I tried from Command prompt and tried other solutions from Google search like assigning a name on shared and trying to delete from network. And nothing worked. That's when I decided, let's take Java's help. Wrote a simple piece of code to loop through until it reaches the final folder and deletes everything. Ran the code and 2 minutes later, everything was gone. One more reason to love Java and being a programmer. Here is the code in case you are interested..



import java.io.File;
public class FileDelete
{

private void deleteFiles(File file)
{
if(file.isDirectory())
{
File child[] = file.listFiles();
for(int i = 0; i < child.length; i++)
{
deleteFiles(child[i]);
}

}
if(!file.delete())
{
System.out.println("Cannot delete file: " + file.getAbsolutePath());
}
}
public static void main(String[] args)
{
System.out.println("Attempting to delete files");
File _work = new File("");
FileDelete fd = new FileDelete();
fd.deleteFiles(_work);
}
}


2 comments:

Anonymous said...

Wow, I had this same exact issue not too long ago and solved it the very same way. I was really glad that it worked, but it left me wondering why Java can delete the files but Windows and DOS can't. Weird.

Anonymous said...

But in real world development ,
it's better to use Apache's commons-io library for file/directory operations.I has many useful methods like FileUtils.cleandirectory() etc.