我正在尝试用
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"); }
解决方法
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(); }