一、API中关于length()的定义
public long length()
Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.
Where it is required to distinguish an I/O exception from the case that 0L is returned, or where several attributes of the same file are required at the same time, then the Fil es.readAttributes method may be used.
当路径为目录时,得到的是一个无法确定的数。当路径为文件时,得到确切的文件大小。
二、递推遍历所有的子目录
public String detail(String dirName){
File file = new File(dirName);
long size = 0;//记录目录的总大小
List<String> fileList = new ArrayList<>();
int i=0;
int count = 0;//记录该初级目录下有多少个文件
if (file.isDirectory()){
fileList.add(file.toString());
for (;i<fileList.size();i++){
File tempFile = new File(fileList.get(i));
if (tempFile.isFile()){
size += tempFile.length();
}else{
File[] files = tempFile.listFiles();
if (i==0){
count = files.length;
}
if (files!=null){//一些文件夹本身就是隐藏的,无法被找到。
for (int j=0;j<files.length;j++){
fileList.add(files[j].toString());
}
}
}
}
return "该文件夹中有"+count+"个文件,总容量为"+size+"字节!";
}
return "查询错误!";
}