欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 删除非空文件夹

程序员文章站 2022-05-15 08:49:34
...

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