I use this code to delete all files:
File root = new File(\"root path\");
File[] Files = root.listFiles();
if(Files != null) {
int j;
for(j = 0; j < F
if storageDir is a directory
for(File tempFile : storageDir.listFiles()) {
tempFile.delete();
}
You can check like this:
for(j = 0; j < Files.length; j++) {
if(file.isDirectory()){
for(File f : file.listFiles()){
System.out.println(Files[j].getAbsolutePath());
System.out.println(Files[j].delete());
}
else {
System.out.println(Files[j].getAbsolutePath());
System.out.println(Files[j].delete());
}
}
Simplest way would be to use FileUtils.deleteDirectory from the Apache Commons IO library.
File dir = new File("root path");
FileUtils.deleteDirectory(dir);
Bear in mind this will also delete the containing directory.
Add this line in gradle file to have Apache
compile 'org.apache.commons:commons-io:1.3.2'
you can try this code to delete files and subfiles
public void deleteFile(File f){
String[] flist=f.list();
for(int i=0;i<flist.length;i++){
System.out.println(" "+f.getAbsolutePath());
File temp=new File(f.getAbsolutePath()+"/"+flist[i]);
if(temp.isDirectory()){
deleteFile(temp) ;
temp.delete();
}else{
temp.delete();
}
As a kotlin extension function you can do this
fun File.deleteDirectoryFiles(){
this.listFiles().forEach {
if(it.isDirectory){
it.deleteDirectoryFiles()
}else{
it.delete()
}
}
this.delete()
}
Then you can just do
file.deleteDirectoryFiles()
For your case, this works perfectly http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#cleanDirectory(java.io.File)
File dir = new File("dir_path");
if(dir.exists() && dir.isDirectory()) {
FileUtils.cleanDirectory(dir);
}
If you wanna delete the folder itself. (It does not have to be empty). Can be used for files too.
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#forceDelete(java.io.File)
File dir = new File("dir_path");
if(dir.exists()) {
FileUtils.forceDelete(dir);
}