I am trying to delete a folder which has only files but no sub folders without success.
File rowFolder = new File(folderPath);
String[] files = r
You could be getting a failed delete for a number of reasons; the file could be locked by the file system, you may lack permissions, or could be open by another process etc.
If you're using Java 7 or above you can use the javax.nio.*
API; it's a little more reliable & consistent than the legacy java.io.File
classes:
Path fp = file.toPath();
Files.delete(fp);
If you want to catch the possible exceptions:
try {
Files.delete(path);
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n", path);
} catch (IOException x) {
// File permission problems are caught here.
System.err.println(x);
}
Check the docs for more info on IO in Java 7
As you aren't checking the return value of delete(), the output you produce is meaningless. The deletion could have failed for any number of reasons:
Try this. Source: How To Delete Directory In Java
import java.io.File;
import java.io.IOException;
public class DeleteDirectoryExample
{
private static final String SRC_FOLDER = "C:\\mkyong-new";
public static void main(String[] args)
{
File directory = new File(SRC_FOLDER);
//make sure directory exists
if(!directory.exists()){
System.out.println("Directory does not exist.");
System.exit(0);
}else{
try{
delete(directory);
}catch(IOException e){
e.printStackTrace();
System.exit(0);
}
}
System.out.println("Done");
}
public static void delete(File file)
throws IOException{
if(file.isDirectory()){
//directory is empty, then delete it
if(file.list().length==0){
file.delete();
System.out.println("Directory is deleted : "
+ file.getAbsolutePath());
}else{
//list all the directory contents
String files[] = file.list();
for (String temp : files) {
//construct the file structure
File fileDelete = new File(file, temp);
//recursive delete
delete(fileDelete);
}
//check the directory again, if empty then delete it
if(file.list().length==0){
file.delete();
System.out.println("Directory is deleted : "
+ file.getAbsolutePath());
}
}
}else{
//if file, then delete it
file.delete();
System.out.println("File is deleted : " + file.getAbsolutePath());
}
}
}
Try this code
public class DeleteDirTest {
public static void main(String[] args) throws IOException {
DeleteDirTest test = new DeleteDirTest();
boolean result = test.deleteDir(new File("D:/test"));
System.out.println(result);
}
public boolean deleteDir(File file) {
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(file, children[i]));
if (!success) {
return false;
}
}
}
return file.delete();
}
}