10

我正在尝试用 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");
          }

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

4

3 回答 3

15

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

}
于 2013-11-23T01:56:49.133 回答
11
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();
}
于 2012-10-11T08:33:16.320 回答
5

您需要先删除目录的内容,然后才能删除目录。您可以尝试以下操作:-

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

    }
}
于 2012-10-11T08:35:27.393 回答