黑马程序员技术交流社区

标题: 统计文件夹大小 [打印本页]

作者: TomZhou    时间: 2016-5-29 00:02
标题: 统计文件夹大小
public class test1 {
/**
  * 从键盘接收一个文件夹路径,统计该文件夹大小
  * @throws IOException
  */
public static void main(String[] args) throws IOException {
  File f1 = getDir();
  //long a = getSize(f1);
  System.out.println(getSize(f1));
}
private static long getSize(File f1) {
  File[] f2 = f1.listFiles();
  long size = 0;
  for (File file : f2) {
   if (file.isFile()) {
    size += file.length();
   }else{
    size+=getSize(file);
   }
   
  }
  return size;
}
public static File getDir() {
  Scanner sc = new Scanner(System.in);
  System.out.println("请输入一个文件夹路径:");
  while (true) {
   String line = sc.nextLine();
   File f1 = new File(line);
   if (!f1.exists()) {
    System.out.println("你录入的不是文件,请重新录入:");
   } else if(f1.isFile()){
    System.out.println("你录入的不是文件路径,请重新录入:");
   }else{
    return f1;
   }
  }
}

}






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2