在Java/JSTL中格式化文件大小

5

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

是否有一个工具类可以做到这一点?
我已经搜索了commons,但没有找到任何东西。有自定义标签吗?
是否已经存在此类库?

理想情况下,我希望它的行为像Unix的ls命令上的-h开关。

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

2个回答

7

我快速搜索了一下,从Apache Hadoop项目中找到了这个。以下是从那里复制的(Apache许可证第2版):

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的情况。


请参考以下链接以获取更简洁的解决方案:https://dev59.com/XG865IYBdhLWcg3wi_Q2 - Niko

6
你可以使用 commons-io 的 FileUtils.byteCountToDisplaySize 方法。如果你在类路径上拥有 commons-io,就可以添加以下标签库函数来实现 JSTL:
<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 -->

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接