java_程序题分析:删除指定目录下的所有文件和文件夹

package 程序题;

import java.io.File;

/**
 * 删除指定目录下的所有文件和文件夹
 * @author 朱方圆
 *
 */
public class T8 {
    
    
	public static void main(String[] args) {
    
    
		
		delFolder("C:\\Users\\Administrator\\Desktop\\1111");//调用delFolder()方法
		
    }
  
	public static boolean delAllFile(String path) {
    
    //创建一个delAllFile()方法
		
		boolean flag = false;//定义boolean类型的变量flag,初始值为false
		
		File file = new File(path);//创建file对象,将传入的路径传给file对象
		
			if (!file.exists()) {
    
    //判断如果file的路径是否存在,不存在,则return flag
				
				return flag;
				
			}
			
			if (!file.isDirectory()) {
    
    //检查file对象是否是一个文件夹,不是就返回flag
				
				return flag;
				
			}
			
			String[] tempList = file.list();//定义一个String类型的数组,将file中的文件列表赋值给当前数组
			
			File temp = null;//定义一个temp,初始为null
			
			for (int i = 0; i < tempList.length; i++) {
    
    //循环遍历tempList数组
				
				if (path.endsWith(File.separator)) {
    
    //文件夹中存在文件
					
					temp = new File(path + tempList[i]);
					
				} else {
    
    
					
					temp = new File(path + File.separator + tempList[i]);
					
				}
				if (temp.isFile()) {
    
    //存在文件,执行删除操作
					
					temp.delete();
					
				}
				if (temp.isDirectory()) {
    
    
					
					delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
					delFolder(path + "/" + tempList[i]);// 再删除空文件夹
					flag = true;
					
				}
			}
			
			return flag;
	}
	
	/***
	 * 删除文件夹
	 * 
	 * @param folderPath文件夹完整绝对路径
	 */
	public  static void delFolder(String folderPath) {
    
    
		
		try {
    
    
			
			delAllFile(folderPath);//删除完里面所有内容
			
			String filePath = folderPath;
			
			filePath = filePath.toString();
			
			java.io.File myFilePath = new java.io.File(filePath);
			
			myFilePath.delete(); // 删除空文件夹
			
		} catch (Exception e) {
    
    
			
			e.printStackTrace();

		}
	}
}


猜你喜欢

转载自blog.csdn.net/zhu_fangyuan/article/details/108292546