文件操作之删除目录文件及子文件

文件操作,删除文件,以前写过n此了,记录下,避免写重复的代码:

/**
	 * 删除指定根目录 
	 * @param fileName
	 */
	public static void delete(String fileName) {
		File file = new File(fileName);
		if (!file.exists()) {
			if (logger.isInfoEnabled()) {
				logger.info("the path is not exist , path : {}" , fileName);
			}
			return ;
		} 
		if (file.isFile()) {
			deleteFile(file);
		} else {
			deleteDir(file);
		}
	}

	/**
	 * 删除文件
	 * @param file
	 */
	private static void deleteFile(File file) {
		long fileSize = file.length();
		long start = System.currentTimeMillis();
		boolean flag = file.delete();
		long end = System.currentTimeMillis();
		if (flag) {
			if (logger.isInfoEnabled()) {
				logger.info("successfully delete file ,file name : {} , file size : {}bytes , cost time : {}ms" , 
						new Object[]{file.getName() , fileSize , (end - start)});
			} 
		} else {
			if (logger.isInfoEnabled()) {
				logger.info("fail delete file ,file name : {}" , file.getName());
			} 
		}
	}

	/**
	 * 删除目录
	 * @param file
	 */
	private static void deleteDir(File file) {
		String[] subPaths = file.list();
		File temp = null;
		for (int i = 0 ; i < subPaths.length ; i++) {
			temp = new File(file.getPath() + File.separator + subPaths[i]);
			if (temp.isFile()) {
				deleteFile(temp);
			} else {
				deleteDir(temp); 
			}
		}
		subPaths = file.list();
		if (null != subPaths && subPaths.length > 0) {
			return ;
		}
		boolean flag = file.delete();
		if (flag) {
			if (logger.isInfoEnabled()) {
				logger.info("successfully delete dir , path : {}" , file.getPath());
			} 
		} else {
			if (logger.isInfoEnabled()) { 
				logger.info("fail delete dir , path : {}" , file.getPath());
			} 
		}
	}


你可能感兴趣的:(文件操作之删除目录文件及子文件)