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
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:
Post a Comment