闂佽 鍋撻柟顖滃椤ワ拷 (0) +1 闁荤姍宥嗗 (0) +1 闂傚⿴浜烽幏锟� (0) +1
闂佽 鍋撻柟顖滃椤ユ垿鏌熺€涙ê濮囧┑顕嗘嫹闂佸搫琚崕鍐诧耿閸涙潙缁╅柟顖滃椤ワ拷>>

正在阅读:遍历目录实现删除,取得大小及深度遍历目录实现删除,取得大小及深度

2004-06-29 09:53 出处:CSDN 作者:shuqianlz 责任编辑:linjixiong

  以下的类就实现了对目录的操作,包括删除,取大小以及深度。



 import java.io.*;
import java.util.*;

public class ManageContent {
  private int dir_deep=0;
  private int dir_size = 0;
  private int sourcepath_deep; //输入路径相对于根目录的深度
  private Hashtable ht=new Hashtable(); //储存输入路径下的所有子目录,及其相对于根目录的深度keys=(String)dirPath,values=(Integer)dirDeep

  public synchronized int getSize(String dir_path) throws FileNotFoundException {
    File dir = new File(dir_path);
    if (!dir.exists()) {
      throw new FileNotFoundException();
    }
    if (!dir.isDirectory()) {
      dir_size = (int) dir.length();
    }
    else {
      File[] fe = dir.listFiles();
      for (int i = 0; i < fe.length; i++) {
        if (fe[i].isDirectory()) {
          getSize(fe[i].toString());
        }
        else {
          dir_size += fe[i].length();
        }
      }
    }
    return dir_size;
  }

 


  public synchronized void deleteFiles(String dir_path) throws FileNotFoundException {
    File file = new File(dir_path);
    if (!file.exists()) {
      throw new FileNotFoundException();
    }
    if (file.isDirectory()) {
      File[] fe = file.listFiles();
      for (int i = 0; i < fe.length; i++) {
        deleteFiles(fe[i].toString());
        fe[i].delete(); //删除已经是空的子目录
      }
    }
    file.delete(); //删除总目录
  }

 


察看评论详细内容 我要发表评论
作者笔名 简短内容 发表时间
:


  private void allDeep(File file){
    File[] fe = file.listFiles();
    for (int i = 0; i < fe.length; i++) {
      if (fe[i].isDirectory()) {
        allDeep(fe[i]); //取得其所有子目录的深度
        ht.put(fe[i].toString(),new Integer(count(fe[i].toString()) - sourcepath_deep));
      }
    }
  }

  public synchronized int getDeep(String dir_path) throws FileNotFoundException{
    File file = new File(dir_path);
    if (!file.exists()) {
      throw new FileNotFoundException();
    }
    if(!file.isDirectory()){
      return -1;  //输入路径不是目录时就返回-1
    }
    sourcepath_deep=count(file.toString());
    allDeep(file);
    Enumeration enum=ht.keys();
    int max=0;
    String keys;
    Integer values;
    while(enum.hasMoreElements()){
      keys=(String)enum.nextElement();
      values=(Integer)ht.get(keys);
      if(values.intValue()>max)
        max=values.intValue();
    }
    return max;
  }

  private int count(String str){
    String regEx="/";
    if(System.getProperty("file.separator").equals("\\"))  //windows和unix下的路径分割符不一样
       regEx="\\\\";
    return str.split(regEx).length;
  }
}



  其中在取目录深度时,我是通过分割字符串来求得其所有子目录相对于根目录的深度,然后再减去输入目录相对于根目录的深度,就得到了输入目录的深度。感觉这个方法执行效率不高,哪位朋友有更好的方法还望不吝赐教。


察看评论详细内容 我要发表评论
作者笔名 简短内容 发表时间
:

相关文章

关注我们

最新资讯离线随时看 聊天吐槽赢奖品
闂佸綊娼ч鍡椻攦閳ь剟鎮规担鍛婂仴婵☆偓鎷�闂佹悶鍎抽崑娑㈠春鐏炰勘浜滈柛顐f礀閸旓拷