package day02;import java.io.File;public class HomeWork09 { public static void main(String[] args) {
File dir = new File("src");
long size1 = getTotalSizeOfFilesInDir(dir);
long size2 = sizeOfDir(dir);
System.out.println("size1:"+size1);
System.out.println("size2:"+size2);
}
//方法1
private static long getTotalSizeOfFilesInDir(File file) {
if (file.isFile()) {
return file.length();
}
File[] children = file.listFiles();
long total = 0;
if (children != null) {
for (File child : children) {
total += getTotalSizeOfFilesInDir(child);
}
}
return total;
}
//方法2
private static long total = 0;
public static long sizeOfDir(File file){
if(file.isFile()){
return file.length();
}
if(file.isDirectory()){
File[] subs = file.listFiles();
for(File sub : subs){
total += sizeOfDir(sub);
}
}
return total;
}}上面是查看一个目录的大小,方法一是网上找的应该是正解,方法二是自己想的,求解为什么方法二为什么是错的!!
File dir = new File("src");
long size1 = getTotalSizeOfFilesInDir(dir);
long size2 = sizeOfDir(dir);
System.out.println("size1:"+size1);
System.out.println("size2:"+size2);
}
//方法1
private static long getTotalSizeOfFilesInDir(File file) {
if (file.isFile()) {
return file.length();
}
File[] children = file.listFiles();
long total = 0;
if (children != null) {
for (File child : children) {
total += getTotalSizeOfFilesInDir(child);
}
}
return total;
}
//方法2
private static long total = 0;
public static long sizeOfDir(File file){
if(file.isFile()){
return file.length();
}
if(file.isDirectory()){
File[] subs = file.listFiles();
for(File sub : subs){
total += sizeOfDir(sub);
}
}
return total;
}}上面是查看一个目录的大小,方法一是网上找的应该是正解,方法二是自己想的,求解为什么方法二为什么是错的!!
----》
因为你的total是静态变量,递归函数多少次,就在上面累加了多少次了。