主要是使用FileUtils.forceDelete(File file)工具类来删除目录下所有东西:
DeleteFolderDemo.java
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class DeleteFolderDemo {
private static Path pathObj = Paths.get("src/test/resources/region/region_test.txt");
public static boolean deleteFolder(File path) {
try {
//1.是文件:则删除
//2.是目录:则“自动”递归删除指定目录下的所有文件和文件夹
FileUtils.forceDelete(file);
return true;
} catch (IOException e) {
return false;
}
public static void main(String[] args) {
}
}
下面是FileUtils.forceDelete(File f)的源代码:
我们可以看到:
是目录:则调用了FileUtils.deleteDirectory(File directory)
是文件:则调用了file.delete()
/**
* Deletes a file. If file is a directory, delete it and all sub-directories.
* <p>
* The difference between File.delete() and this method are:
* <ul>
* <li>A directory to be deleted does not have to be empty.</li>
* <li>You get exceptions when a file or directory cannot be deleted.
* (java.io.File methods returns a boolean)</li>
* </ul>
*
* @param file file or directory to delete, must not be {@code null}
* @throws NullPointerException if the directory is {@code null}
* @throws FileNotFoundException if the file was not found
* @throws IOException in case deletion is unsuccessful
*/
public static void forceDelete(File file) throws IOException {
if (file.isDirectory()) {
deleteDirectory(file);
} else {
boolean filePresent = file.exists();
if (!file.delete()) {
if (!filePresent){
throw new FileNotFoundException("File does not exist: " + file);
}
String message =
"Unable to delete file: " + file;
throw new IOException(message);
}
}
}
ps:
若想调用FileUtils.deleteDirectory(File directory)
注意:参数一定是目录,不能是指定文件!!否则报错:*** is not a directory