質問

    

この質問にはすでに回答があります:

         

Java / JSP / JSTLページでファイルサイズをフォーマットする良い方法を誰かが知っているのかと思っていました。

これを行うutilクラスはありますか?
コモンズを検索しましたが、何も見つかりませんでした。カスタムタグはありますか?
このためのライブラリは既に存在しますか?

理想的には、Unixの ls コマンドの -h スイッチのように動作させたい

34-<!> gt; 34
795-<!> gt; 795
2646-<!> gt; 2.6K
2705-<!> gt; 2.7K
4096-<!> gt; 4.0K
13588-<!> gt; 14K
28282471-<!> gt; 27M
28533748-<!> gt; 2,800万

役に立ちましたか?

解決

クイックGoogle検索で返された 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を使用して<!> lt; 1024ケースを処理する必要があります。

他のヒント

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 -->
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top