Java 如何获得以字节为单位的文件大小 KB MB GB TB

x33g5p2x  于2022-10-06 转载在 其他  
字(1.0k)|赞(0)|评价(0)|浏览(503)

1. 概述

在这个例子中,我们将写一个通用的方法来获取文件的大小,单位是字节、千字节、百万字节、GB、TB。

2. 文件大小的单位是B,KB,MB,GB和TB 示例

  1. 例子中的readableFileSize()方法,以长类型传递文件的大小。
  2. readableFileSize()方法返回代表文件大小的字符串(B,KB,MB,GB,TB)。
import java.io.File;
import java.text.DecimalFormat;

/**
* This Java program demonstrates how to get file size in bytes, kilobytes, mega bytes, GB,TB.
* @author javaguides.net
*/

public class FileUtils {
 /**
* Given the size of a file outputs as human readable size using SI prefix.
* <i>Base 1024</i>
* @param size Size in bytes of a given File.
* @return SI String representing the file size (B,KB,MB,GB,TB).
*/
    public static String readableFileSize(long size) {
        if (size <= 0) {
            return "0";
        }
        final String[] units = new String[] {"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int)(Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) 
          + " " + units[digitGroups];
    }
    
    public static void main(String[] args) {
     File file = new File("sample.txt");
     String size = readableFileSize(file.length());
     System.out.println(size);
    }
}

输出。

64 B

增加文件并再次测试。

164 KB

相关文章

微信公众号

最新文章

更多