Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Tuesday, September 16, 2014

Java program to delete all files from a folder (without deleting the folder)

Below program demonstrate on how to delete all files from a folder. This program will delete all the files in the given directory and all sub directories which are empty. It will not delete any of the sub directories which are not empty.


import java.io.*;
class DeleteFilesFromFolder
{
public static void deleteAllFiles(String pathToDelete)
{

try
{
File f=new File(pathToDelete);
File [] file=f.listFiles();
for(File fileTodelete:file)
{
fileTodelete.delete();
}

if(f.list().length>0)
{
System.out.println("All files not deleted");
}
else
{
System.out.println("All files deleted");
}
}
catch (Exception i)
{
System.out.println(i.getMessage());
}

}

public static void main(String[] args)
{
deleteAllFiles("C:\\Users\\DHT\\Desktop\\Delete");
}
}


Result after successful execution



No comments: