package cn.tedu.homework;
import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Scanner;
public class Dir {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入要遍历的文件夹:");
File file = new File(sc.next());
fileRecursion(file);
}
public static void fileRecursion(File file) {
if (!file.exists()) {
System.err.println("此路径不存在");
return;
} else if (file.isDirectory()) {
File[] listFiles = file.listFiles();
if (listFiles != null) {
for (int i = 0; i < listFiles.length; i++) {
if (listFiles[i].isFile()) {
System.out.println(listFiles[i].getName() + '\t' + fileSize(listFiles[i].length()));
} else {
System.out.println(listFiles[i].getAbsolutePath());
fileRecursion(listFiles[i]);
}
}
}
} else {
System.out.println(file.getName() + '\t' + fileSize(file.length()));
}
}
private static String fileSize(long length) {
BigDecimal size = new BigDecimal(length + "");
BigDecimal divisor = new BigDecimal(1024 + "");
if(length >= 1024 * 1024 * 1024){
return size.divide(divisor, 2, RoundingMode.HALF_UP)
.divide(divisor, 2, RoundingMode.HALF_UP)
.divide(divisor, 2, RoundingMode.HALF_UP) + "GB";
}else if(length >= 1024 * 1024){
return size.divide(divisor, 2, RoundingMode.HALF_UP)
.divide(divisor, 2, RoundingMode.HALF_UP) + "MB";
}else if(length >= 1024) {
return size.divide(divisor, 2, RoundingMode.HALF_UP) + "KB";
}
return length + "B";
}
}
|