【问题标题】:Java if-else statement to print file/directory size; large file size (1 GB<) printing issueJava if-else 语句打印文件/目录大小;大文件大小 (1 GB<) 打印问题
【发布时间】: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


    【解决方案1】:

    尝试使用 int 类型而不是 long。如果最大。类型的大小是瓶颈,它应该可以解决你的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-29
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 2012-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多