创建目录.如果存在,请删除目录及其内容,然后用Java创建新目录 [英] Create directory. If exists, delete directory and its content and create new one in Java

查看:72
本文介绍了创建目录.如果存在,请删除目录及其内容,然后用Java创建新目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

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

这篇关于创建目录.如果存在,请删除目录及其内容,然后用Java创建新目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆