Question

I am trying to delete a folder which has only files but no sub folders without success.

Code:

File rowFolder = new File(folderPath);
String[] files = rowFolder.list();
for (String file : files){
    File deleteFile = new File(file);
    System.out.println("deleting file -"+deleteFile.getName());
    deleteFile.delete();
}
System.out.println("deleting folder -"+rowFolder.getName());
rowFolder.delete();

Output:

deleting file -testing.pdf
deleting file -app_json.json
deleting file -photo.jpg
deleting folder -bundle_folder

The code doesn't delete any folder nor any file. Why is that?

Était-ce utile?

La solution

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.Fileclasses:

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

Autres conseils

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:

  • the file is a non-empty directory
  • the file is open by another user (on some platforms)
  • you don't have permission to delete that file.

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();
    }

}

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());
        }
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top