public class filetest {
public static void main(String[] agrs){
File file = new File("file");
System.out.println(countTotalFileSize(file));
// //读取目录下的所有文件
// File[] s = file.listFiles();
// for (int i = 0; i < s.length; i++) {
// System.out.println(s[i].getName());
// }
//deleteDir(file);
}
//递归删除文件夹
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
//递归删除子目录下的文件
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// 目录此时为空,可以删除
return dir.delete();
}
//递归计算文件大小
public static long countTotalFileSize(File file){
if (file.isFile()){
return file.length();
}
long total = 0;
if (file.isDirectory()){
File[] children = file.listFiles();
for (int i = 0; i < children.length; i++) {
total += countTotalFileSize(children[i]);
}
}
return total;
}
}
Java本地文件删除和计算文件大小
最新推荐文章于 2025-05-19 17:56:31 发布