Cannot delete folder using Java

前端 未结 4 891
孤城傲影
孤城傲影 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:48

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

提交回复
热议问题