[Java]求文件大小并保留两位小数(文件大小是一个长整型数单位是Byte)

前言

为了获得一堆apk的大小,并与人类友好方式显示。本来是打算用以下方法,到时不能具体到保留两位小数。

org.apache.commons.io.FileUtils.byteCountToDisplaySize(f.length());

  Returns a human-readable version of the file size, where the input represents a specific number of bytes.

  If the size is over 1GB, the size is returned as the number of whole GB, i.e. the size is rounded down to the nearest GB boundary.

  Similarly for the 1MB and 1KB boundaries. 

代码

File f = new File("D:/apps/helloworld.apk");
String sizeStr = CommonUtils.longToString(f.length());
String sizeShow = longToString(sizeStr);
public static String longToString(long size) {

            long kb = 1024;
            long mb = kb * 1024;
            long gb = mb * 1024;
            String ret = "";
            
            DecimalFormat df = new DecimalFormat("0.00");
            
            if(size >= gb){
                ret = df.format(size/(gb*1.0)) + " GB";
            }else if(size >= mb){
                ret = df.format(size/(mb*1.0)) + " MB";
            }else if(size >= kb){
                ret = df.format(size/(kb*1.0)) + " KB";
            }else if(size > 0){
                ret = df.format(size/(1.0)) + " Byte";
            }
            
            return ret;
    } 

分析

gb*1.0是为了让long类型转换成double类型,然后整除后的结果也是double类型。其它

结语

其它文件类型的文件处理方式一致。

原文地址:https://www.cnblogs.com/fanbi/p/7020028.html