2009-04-29 40 views
4

我想知道是否有人知道在Java/JSP/JSTL页面中格式化文件大小的好方法。在Java/JSTL中格式化文件大小

有没有这样做的util类?
我已经搜寻了commons,但什么也没找到。任何自定义标签?
这个库是否已经存在?

理想我想它表现像-h交换机上Unix的LS命令

34 - > 34
795 - > 795
2646 - > 2.6K
2705 - > 2.7K
4096 - > 4.0K
13588 - > 14K
28282471 - > 27M
28533748 - > 28M

回答

6

快速谷歌搜索从Appache hadoop项目返回我this。从那里复制: (Apache许可证,版本2.0):

private static DecimalFormat oneDecimal = new DecimalFormat("0.0"); 

    /** 
    * Given an integer, return a string that is in an approximate, but human 
    * readable format. 
    * It uses the bases 'k', 'm', and 'g' for 1024, 1024**2, and 1024**3. 
    * @param number the number to format 
    * @return a human readable form of the integer 
    */ 
    public static String humanReadableInt(long number) { 
    long absNumber = Math.abs(number); 
    double result = number; 
    String suffix = ""; 
    if (absNumber < 1024) { 
     // nothing 
    } else if (absNumber < 1024 * 1024) { 
     result = number/1024.0; 
     suffix = "k"; 
    } else if (absNumber < 1024 * 1024 * 1024) { 
     result = number/(1024.0 * 1024); 
     suffix = "m"; 
    } else { 
     result = number/(1024.0 * 1024 * 1024); 
     suffix = "g"; 
    } 
    return oneDecimal.format(result) + suffix; 
    } 

它采用1K = 1024,但如果你喜欢,你可以适应这一点。您还需要使用不同的DecimalFormat处理< 1024个案例。

+0

看到http://stackoverflow.com/问题/ 3758606 /如何将字节大小转换为人类可读格式的Java中更清洁的解决方案 – Niko 2013-06-18 07:01:16

5

您可以使用commons-io FileUtils.byteCountToDisplaySize方法。对于JSTL实现,而在你的类路径中的commons-io的,你可以添加下面的taglib功能:

<function> 
    <name>fileSize</name> 
    <function-class>org.apache.commons.io.FileUtils</function-class> 
    <function-signature>String byteCountToDisplaySize(long)</function-signature> 
</function> 

现在,在你的JSP,你可以这样做:

<%@ taglib uri="/WEB-INF/FileSizeFormatter.tld" prefix="sz"%> 
Some Size: ${sz:fileSize(1024)} <!-- 1 K --> 
Some Size: ${sz:fileSize(10485760)} <!-- 10 MB -->