创建目录。如果存在,删除目录及其内容并在 Java 中创建新目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12835285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:24:32  来源:igfitidea点击:

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

javadirectory

提问by Intern

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.

我正在尝试用 Java 创建一个目录。如果存在,我想删除该目录及其内容并创建一个新目录。我正在尝试执行以下操作,但未删除该目录。新文件将附加到目录中。

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.

我正在运行时在运行项目的目录中创建这个目录。每次运行后,必须删除旧内容,新内容必须存在于该目录中。

回答by Chris

Thanks to Apache this is super easy.

感谢 Apache,这非常容易。

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

}

回答by urir

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

回答by Rohit Jain

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

    }
}