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

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

程序员文章站 2024-03-09 14:45:11
实例如下: package com.xx; import java.io.file; public class test { public s...

实例如下:

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 删除文件夹中的所有内容而不删除文件夹本身的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。