java删除文件夹

/*

 * Author:   
 * Date:     2016年10月24日 上午9:56:41  
 */

import java.io.File;
import java.nio.file.Files;

/**
 * @date 2016年10月24日 上午10:00:11

 */
public class DeleteLongFolder {
    public static int length;
    public static String path = "D:\\temp";// 取出来的文件夹的存放位置
    public static File tempFile = new File(path);
    static {
        if (!tempFile.exists()) {
            tempFile.mkdirs();
        }
    }

    public static void main(String[] args) {
        delete("D:\\新建文件夹");
    }

    public static void delete(String waitToDelPath) {
        long start=System.currentTimeMillis();
        File file = new File(waitToDelPath);/* 路径过长的文件夹 */
        delDir(file, tempFile);
        tempFile.delete();
        System.out.println("cost:"+(System.currentTimeMillis()-start)+"ms");
    }

    public static void delDir(File file, File tempFile) {
        if (file == null || tempFile == null) {
            return;
        }
        File tofile = new File(path, "" + length);  
        length++;
        System.out.println("mv " + file.getAbsolutePath() + " to " + tofile.getAbsolutePath());
        if (file.isFile()) { 
            if (!file.renameTo(tofile)) {
                System.out.println("mv fail:"+file.getAbsolutePath()+" to "+tofile.getAbsolutePath());
            }
            delEmptyDirOrFile(tofile);
            return;
        } else {
            File[] listFile = file.listFiles();
            if (listFile == null) {
                if (!file.renameTo(tofile)) {
                    System.out.println("mv fail:"+file.getAbsolutePath()+" to "+tofile.getAbsolutePath());
                }
                delEmptyDirOrFile(tofile);
                return;
            } else {
                for (File file2 : listFile) {
                    delDir(file2, tempFile);
                }
                if (!file.renameTo(tofile)) {
                    System.out.println("mv fail:"+file.getAbsolutePath()+" to "+tofile.getAbsolutePath());
                }
                delEmptyDirOrFile(tofile);
            }
        }
    }
    
    public static boolean  delEmptyDirOrFile(File waitToDelFile){
        if(!waitToDelFile.delete()){
            System.out.println("del fail:" + waitToDelFile.getPath());
            return false;
        }
        return true;
    }
}

猜你喜欢

转载自974336041.iteye.com/blog/2332862