【发布时间】:2023-01-05 17:19:01
【问题描述】:
我想用 Java 打印文件/目录大小,但是对于大于 1GB 的文件我不能。大概是 long 类型的最大限制?请教我,代码如下:
long size;
String notation;
if (file.isDirectory()) {
// File is a directory, calculate size of all files in the directory
size = 0;
for (File f : file.listFiles()) {
size += f.length();
}
} else {
// File is a regular file, use size of file
size = file.length();
}
// Conversion
long bytes = size;
long kilobytes = (bytes / 1024);
long megabytes = (kilobytes / 1024);
long gigabytes = (megabytes / 1024);
long terabytes = (gigabytes / 1024);
long petabytes = (terabytes / 1024);
long exabytes = (petabytes / 1024);
//long zettabytes = (exabytes / 1024);
//long yottabytes = (zettabytes / 1024);
if (size > 0 && size < kilobytes){
notation = "B";
System.out.println(size+notation);
} else if (size > kilobytes && size < megabytes) {
// file is smaller than 1 MB, return size in KB
size /= 1024;
notation = "KB";
System.out.println(size+notation);
} else if (size > megabytes && size < gigabytes) {
// file is smaller than 1 GB, return size in MB
notation = "MB";
size /= 1024.0 * 1024;
System.out.println(size+notation);
} else if (size > gigabytes && size < terabytes) {
// file is larger than 1 GB, return size in GB
notation = "GB";
size /= 1024.0 * 1024.0 * 1024.0;
System.out.println(size+notation);
} else {
// file is larger than 1 TB, return size in TB
notation = "TB";
size /= 1024.0 * 1024.0 * 1024.0 * 1024;
System.out.println(size+notation);
}
// cast size to double before passing it to String.format
return String.format("[Size: %.3f %s]", (double) size, notation);
}
【问题讨论】:
标签: java file if-statement size filesize