服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

遍历目录实现删除,取得大小及深度

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





 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;
  }
}



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





扫描关注微信公众号