5

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

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

理想的には、Unix のlsコマンドの-hスイッチのように動作することを望みます

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

4

2 に答える 2

7

簡単なGoogle検索で、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 のケースを処理する必要があります。

于 2009-04-29T11:47:27.887 に答える