A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© TomZhou 中级黑马   /  2016-5-29 00:02  /  443 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

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

}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马