Create directory If so, delete the directory and its contents and create a new directory in Java

I'm trying to create a directory in Java If it exists, I want to delete the directory and its contents and create a new directory I tried to do the following without deleting the directory The new file will be attached 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 create this directory in the directory of the running project at run time After each run, the old content must be deleted and the new content must be displayed in this directory

Solution

public static boolean deleteDir(File dir) {
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();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>