android递归遍历时候可能会造成 java.lang.StackOverflowError,且速度较慢,自己写了个东西,测试可用。
public static long getFileSize(String path) {
long now = System.currentTimeMillis();
Log.i("test", "getFileSize-now:" + now);
long mbyte = 0;
ArrayList<String> dirpaths = new ArrayList<String>();
File r_f = new File(path);
if (r_f.isDirectory()) {
dirpaths.add(path);
while (dirpaths.size() > 0) {
File f = new File(dirpaths.get(0));
File[] fs = f.listFiles();
for (File ff : fs) {
Log.i("te_st", ff.getName());
if (ff.isDirectory()) {
dirpaths.add(ff.getAbsolutePath());
} else {
mbyte += ff.length();
}
}
dirpaths.remove(0);
}
} else {
mbyte += r_f.length();
}
long end = System.currentTimeMillis();
Log.i("test", "getFileSize-end:" + end);
Log.i("test", "getFileSize-curren:" + (end - now));
return mbyte;
}