---
title: "删除文件夹和统计文件夹大小"
author: "lost_alien"
date: "2009-05-15T11:08:56Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2009-05-15T11:08:56Z"
id: 387289
url: "https://lost-alien.iteye.com/blog/387289"
---

```java

//删除文件夹
    public static void fileDelete(File file) throws Exception {
        if (!file.exists()) {
            log.debug("文件或目录不存在！");
            return;
        }

        if (file.isFile()) {
            if (!file.delete())
                throw new Exception("文件无法删除！");
            return;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files.length == 0) {
                if (!file.delete())
                    throw new Exception("目录无法删除！");
                return;
            }
            for (int i = 0; i < files.length; i++) {
                File subFile = files[i];
                FileHandler.fileDelete(subFile);
            }
            if (!file.delete())
                throw new Exception("目录无法删除！");
        }
        return;
    }
    //统计文件夹的大小，返回结果以 兆 为单位，调用此方法时，totalSize要传 零
    public  static long fileSize(File file, long totalSize)  {

        if (!file.exists()) {
            log.info("文件或目录不存在！");
            return totalSize;
        }

        if (file.isFile()) {
            //log.debug( file.getName() );
            totalSize += file.length() / 1024 / 1024;
            return totalSize;
        }

        if (file.isDirectory()) {
            File[] subFiles = file.listFiles();
            if (subFiles.length == 0)
                return totalSize;
            for (int i = 0; i < subFiles.length; i++) {
                totalSize = FileHandler.fileSize(subFiles[i], totalSize);
            }
        }
        return totalSize;

    }

```