Java 中如何删除非空的目录呢?
使用递归,代码如下:
- /***
- * delete a directory/folder
- *
- * @param someFile
- */
- public static boolean deleteDir(File someFile) {
- if (!someFile.exists()) {
- System.out.println("[deleteDir]File " + someFile.getAbsolutePath()
- + " does not exist.");
- return false;
- }
- if (someFile.isDirectory()) {// is a folder
- File[] files = someFile.listFiles();
- for (File subFile : files) {
- boolean isSuccess = deleteDir(subFile);
- if (!isSuccess) {
- return isSuccess;
- }
- }
- } else {// is a regular file
- boolean isSuccess = someFile.delete();
- if (!isSuccess) {
- return isSuccess;
- }
- }
- if (someFile.isDirectory()) {
- return someFile.delete();
- } else {
- return true;
- }
- }
说明:若删除成功,则返回true,否则返回false