I have a folder that contains picture files.
I use File.deleteRecursively()
to delete the files, and it works perfectly,
but I must delete the content, not the 'Pictures' folder itself. How can that be done?
CodePudding user response:
This should work
private static void deleteDirContent(String path){
File f = new File(path);
File[] allFiles = f.listFiles();
if(allFiles == null)
return;
for (File f2 :
allFiles) {
if(f2.isFile()) {
if (f2.delete()) {
// this means file is deleted, everything is good
} else {
// was unable to delete the file, handle accordingly.
}
}
else{
f2.deleteRecursively();
}
}
}
Make sure you have the right permissions of course. For some reason I don't have deleteRecursively function, if it's Kotlin implementation then for Java you can add this function:
private static void deleteDirContentWithDir(String path){
File f = new File(path);
File[] allFiles = f.listFiles();
if(allFiles == null)
return;
for (File f2 :
allFiles) {
if(f2.isFile()) {
if (f2.delete()) {
// this means file is deleted, everything is good
} else {
// was unable to delete the file, handle accordingly.
}
}
else{
deleteDirContentWithDir(f2.getAbsolutePath());
}
}
f.delete();
}
This will delete the dir content. In general, you can combine them to a single function:
private static void deleteDirContent(String path, boolean delWithDir){
File f = new File(path);
File[] allFiles = f.listFiles();
if(allFiles == null)
return;
for (File f2 :
allFiles) {
if(f2.isFile()) {
if (f2.delete()) {
// this means file is deleted, everything is good
} else {
// was unable to delete the file, handle accordingly.
}
}
else{
deleteDirContent(f2.getAbsolutePath(), true);
}
}
if(delWithDir)
f.delete();
}
This basically says, delete a directory content, including directories that might have content and lets you decide if you want to delete the directory it self using the boolean parameter
CodePudding user response:
If you can use Kotlin version 1.8 or later, there is a new extension function on java.nio.files.Path
which is preferable to File.deleteRecursively
because it gives you more information (through exceptions) when a file cannot be deleted. It is currently "experimental":
import kotlin.io.path.*
@OptIn(ExperimentalPathApi::class)
fun deleteDirectoryContents(dir: String) {
Path(dir).forEachDirectoryEntry { it.deleteRecursively() }
}