package e.io.practice;
import java.io.File;
import java.text.DecimalFormat;
public class FileSizeSummary {
public static void main(String[] args) {
FileSizeSummary sample = new FileSizeSummary();
String path = "C:\\godofjava";
long sum = sample.printFileSize(path);
System.out.println(path+"'s total size= " + sample.convertFileLength(sum));
}
public long printFileSize(String dirName) {
File file = new File(dirName);
long sum=0;
if(file.isDirectory()) {
File[] fileList = file.listFiles();
for(File files : fileList) {
if(files.isFile()) {
String tempFileName = files.getAbsolutePath();
long fileLength = files.length();
sum += fileLength;
} else {
String tempDirName = files.getAbsolutePath();
long fileLength = printFileSize(tempDirName);
System.out.println("["+tempDirName+"]= "+convertFileLength(fileLength));
sum+=fileLength;
}
}
} return sum;
}
private String convertFileLength(long fileLength) {
DecimalFormat decimal = new DecimalFormat("####.##");
String size;
if(fileLength <=1024) {
size = decimal.format(fileLength) +" b";
} else if(fileLength<=(1024*1024)) {
size = decimal.format(1.0 * fileLength / 1024) +" kb";
} else if(fileLength <= (1024*1024*1024)) {
size = decimal.format(1.0 * fileLength / (1024 * 1024)) +" mb";
} else {
size = decimal.format(1.0 * fileLength / (1024 * 1024 * 1024)) +" gb";
}
return size;
}
}
'Java' 카테고리의 다른 글
자바의 신 ch30 (0) | 2022.07.16 |
---|---|
자바의신 ch27 ~ ch29 (0) | 2022.07.13 |
자바의신 ch25 (0) | 2022.07.07 |
자바의신 ch24 (0) | 2022.07.06 |
자바의 신 CH22 & CH23 (0) | 2022.07.05 |