首页 > 学院 > 开发设计 > 正文

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

2019-11-17 06:10:58
字体:
来源:转载
供稿:网友
  以下的类就实现了对目录的操作,包括删除,取大小以及深度。





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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表