Tuesday, September 16, 2014

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

2:58 PM

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



0 comments :

Post a Comment

 

© 2014 DieHardTechy . All rights resevered. Designed by Diehardtechy