这个问题在这里已经有答案了:

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

有没有一个 util 类可以做到这一点?
我搜索过公共资源但一无所获。有自定义标签吗?
是否已经存在用于此目的的库?

理想情况下,我希望它的行为像 -H 打开 Unix 的 LS 命令

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

有帮助吗?

解决方案

快速的谷歌搜索让我回来了 来自 Appache hadoop 项目。从那里复制:(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 的情况。

其他提示

您可以使用commons-io FileUtils.byteCountToDisplaySize 方法。对于 JSTL 实现,您可以添加以下 taglib 函数,同时在类路径上添加 commons-io:

<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 -->
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top