Create directory. If exists, delete directory and its content and create new one in Java

限于喜欢 提交于 2019-12-23 07:58:13

问题


I am trying to make a directory in Java. If it exists, I want to delete that directory and its content and make a new one. I am trying to do the following, but the directory is not deleted. New files are appended to the directory.

File file = new File("path");
boolean isDirectoryCreated = file.mkdir();
   if (isDirectoryCreated) {
       System.out.println("successfully made");
        } else {
          file.delete();
          file.mkdir();
          System.out.println("deleted and made");
          }

I am creating this directory in runtime in the directory of the running project. After every run, the old contents have to be deleted and new content has to be present in this directory.


回答1:


public static boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i=0; i<children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }
    return dir.delete();
}



回答2:


Thanks to Apache this is super easy.

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class DeleteFolder {

    public static void main(String[] args){
        try {
            File f = new File("/var/www/html/testFolder1");
            FileUtils.cleanDirectory(f); //clean out directory (this is optional -- but good know)
            FileUtils.forceDelete(f); //delete directory
            FileUtils.forceMkdir(f); //create directory
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }

}



回答3:


You need to delete first the contents of the directory then only you can delete the directory.. You can try something like this: -

File file = new File("path");
boolean isDirectoryCreated = file.mkdir();

if (isDirectoryCreated) {
       System.out.println("successfully made");

} else {
       deleteDir(file);  // Invoke recursive method
       file.mkdir();       
}


public void deleteDir(File dir) {
    File[] files = dir.listFiles();

    for (File myFile: files) {
        if (myFile.isDirectory()) {  
            deleteDir(myFile);
        } 
        myFile.delete();

    }
}


来源:https://stackoverflow.com/questions/12835285/create-directory-if-exists-delete-directory-and-its-content-and-create-new-one

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!