前言
代码功能:获取某目录下文件总大小
项目中不仅需要判断磁盘大小,还需要限制拷贝目录大小。
正文
思路:递归目录下的所有文件,累加文件大小。
当然,这种递归方式不是很好,因为存在目录层级复杂和文件多,导致耗时。
/**
*
* @param file
* @return
*/
public static double getDirSize(File file) {
if (null != file && file.exists()) {
if (file.isDirectory()) {
File[] files = file.listFiles();
double length = 0;
for (File f : files) {
length += getDirSize(f);
}
return length;
} else {
return (double) file.length();
}
} else {
return 0.0;
}
}
![[摘]Android多语言目录对照表](https://www.biumall.com/wp-content/themes/BiuX/assets/images/random/0.webp)