- import java.io.*;
- class TestThread extends Thread {
- private String[] args;
- public boolean deleteFile(String sPath) {
- boolean flag = false;
- File file = new File(sPath);
- // 路径为文件且不为空则进行删除
- if (file.isFile() && file.exists()) {
- file.delete();
- flag = true;
- }
- return flag;
- }
- public boolean deleteDirectory(String sPath) {
- //如果sPath不以文件分隔符结尾,自动添加文件分隔符
- if (!sPath.endsWith(File.separator)) {
- sPath = sPath + File.separator;
- }
- File dirFile = new File(sPath);
- //如果dir对应的文件不存在,或者不是一个目录,则退出
- if (!dirFile.exists() || !dirFile.isDirectory()) {
- return false;
- }
- boolean flag = true;
- //删除文件夹下的所有文件(包括子目录)
- File[] files = dirFile.listFiles();
- for (int i = 0; i < files.length; i++) {
- if (files[i].isFile()) {
- flag = deleteFile(files[i].getAbsolutePath());
- if (!flag) break;
- } else {
- flag = deleteDirectory(files[i].getAbsolutePath());
- if (!flag) break;
- }
- }
- if (!flag) return false;
- //删除当前目录
- if (dirFile.delete()) {
- return true;
- } else {
- return false;
- }
- }
- public boolean DeleteFolder(String sPath) {
- boolean flag = false;
- File file = new File(sPath);
- // 判断目录或文件是否存在
- if (!file.exists()) { // 不存在返回 false
- System.out.println(sPath + " not exist");
- return flag;
- } else {
- // 判断是否为文件
- if (file.isFile()) { // 为文件时调用删除文件方法
- return deleteFile(sPath);
- } else { // 为目录时调用删除目录方法
- return deleteDirectory(sPath);
- }
- }
- }
- public TestThread(String[] args) {
- this.args = args;
- }
- public void run() {
- int i;
- for (i = 0; i < args.length; i++) {
- System.out.println("Delete " + args[i]);
- DeleteFolder(args[i]);
- }
- }
- }
- public class Del {
- public static void main(String[] args) {
- new TestThread(args).start();
- System.out.println(Runtime.getRuntime().availableProcessors() + " cpus");
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/2212201411363.html
来源: http://www.codesnippet.cn/detail/2212201411363.html