zoukankan      html  css  js  c++  java
  • [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类型。其它

    结语

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

  • 相关阅读:
    最好的委托与事件详解一(转自张子阳博客)
    事务处理两种方式(转自一壶茶水)
    条目列表点击效果
    html可变大小字体
    udp群聊
    vbs隐藏运行bat之木马合体
    淘宝客网站的链接跳转形式
    工作之外八小时,用辛苦换幸福
    怕吃苦,吃苦一辈子
    外链建设的六个方法
  • 原文地址:https://www.cnblogs.com/fanbi/p/7020028.html
Copyright © 2011-2022 走看看