Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Jan 6, 2000

Recursively Delete Directories in Java

In Java, a readable, writable directory should be empty before an attempt is made to remove it. The following code recursively empties a directory, and its sub-directories, and then removes them.
 
private void deleteFile(File p_file) 
{ 
String FILE_SEPARATOR = System.getProperty("file.separator"); 
// If it is a directory, empty it first 
System.out.println("Deleting: "+p_file.getPath()); 
if(p_file.isDirectory()) 
{ 
String[] dirList = p_file.list(); 
for(int i=0; i<dirList.length; i++) 
{ 

File aFile = new File(p_file.getPath()+FILE_SEPARATOR+dirList[i]); 
if(aFile.isDirectory()) 
{ 
deleteFile(aFile); 
} 
aFile.delete(); 
} 
} 
p_file.delete(); 
} 
Note that a File object should be writable by the current user of the code in order to be removed.
Behrouz Fallahi
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date