Cannot delete folder using Java

前端 未结 4 933
孤城傲影
孤城傲影 2021-01-22 17:20

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 = r         


        
4条回答
  •  臣服心动
    2021-01-22 17:44

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

提交回复
热议问题