当前位置: 移动技术网 > IT编程>开发语言>Java > java 删除文件夹中的所有内容而不删除文件夹本身的实例

java 删除文件夹中的所有内容而不删除文件夹本身的实例

2019年07月22日  | 移动技术网IT编程  | 我要评论

实例如下:

package com.xx;

import java.io.file;

public class test {

	public static void main(string[] args) {
		string fileroot = "c:/users/xx/desktop/xx/xxx";
	  delfolder(fileroot);
      system.out.println("deleted");
	}

//	// 删除完文件后删除文件夹
//	// 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();
		}
	}

	// 删除指定文件夹下所有文件
	// param path 文件夹完整绝对路径
	public static boolean delallfile(string path) {
		boolean flag = false;
		file file = new file(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isdirectory()) {
			return flag;
		}
		string[] templist = file.list();
		file temp = null;
		for (int i = 0; i < templist.length; i++) {
			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;
	}
}

以上这篇java 删除文件夹中的所有内容而不删除文件夹本身的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网