Пример #1
0
 public long getLongSize() throws RuntimeException {
   try {
     // 调用计算文件或目录大小方法
     getFileSize();
     return longSize;
   } catch (IOException ex) {
     ex.printStackTrace();
     throw new RuntimeException(ex.getMessage());
   }
 }
Пример #2
0
  // 返回文件大小
  private void getFileSize() throws RuntimeException, IOException {
    // 初始化文件大小为0;
    this.longSize = 0;

    // 如果文件存在而且是文件,直接返回文件大小
    if (file.exists() && file.isFile()) {
      this.longSize = file.length();

      // 文件存在而且是目录,递归遍历文件目录计算文件大小
    } else if (file.exists() && file.isDirectory()) {
      getFileSize(file); // 递归遍历
    } else {

    }
  }
Пример #3
0
  public String toString() throws RuntimeException {
    try {
      // 调用计算文件或目录大小方法
      try {
        getFileSize();
      } catch (RuntimeException e) {
        return "";
      }

      return convertSizeToString(this.longSize);

    } catch (IOException ex) {
      ex.printStackTrace();
      throw new RuntimeException(ex.getMessage());
    }
  }
Пример #4
0
 // 递归遍历文件目录计算文件大小
 private void getFileSize(File file) throws RuntimeException, IOException {
   // 获得文件目录下文件对象数组
   File[] fileArray = file.listFiles();
   // 如果文件目录数组不为空或者length!=0,即目录为空目录
   if (fileArray != null && fileArray.length != 0) {
     // 遍历文件对象数组
     for (int i = 0; i < fileArray.length; i++) {
       File fileSI = fileArray[i];
       // 如果是目录递归遍历
       if (fileSI.isDirectory()) {
         // 递归遍历
         getFileSize(fileSI);
       }
       // 如果是文件
       if (fileSI.isFile()) {
         this.longSize += fileSI.length();
       }
     }
   } else {
     // 如果文件目录数组为空或者length==0,即目录为空目录
     this.longSize = 0;
   }
 }