Domanda

A questa domanda ha già una risposta qui:

Mi chiedevo se qualcuno sapesse di un buon modo per formattare le dimensioni dei file in Java/JSP/JSTL pagine.

C'è un util classe che fare con questo?
Ho cercato commons, ma non trovai nulla.Qualsiasi tag personalizzati?
Non una libreria già esistente per questo?

Idealmente mi piacerebbe che si comportano come il -h interruttore di Unix ls comando

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

È stato utile?

Soluzione

Una rapida ricerca su google mi ha restituito questo da Appache hadoop progetto.Copia da qui:(Licenza Apache, Versione 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;
  }

Utilizza 1K = 1024, ma si può adattare questo, se si preferisce.È necessario gestire il <1024 caso con un diverso DecimalFormat.

Altri suggerimenti

È possibile utilizzare i commons-io FileUtils.byteCountToDisplaySize i metodi.Per un JSTL attuazione è possibile aggiungere i seguenti taglib funzione, pur avendo commons-io sul tuo classpath:

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

Ora nella pagina JSP si può fare:

<%@ taglib uri="/WEB-INF/FileSizeFormatter.tld" prefix="sz"%>
Some Size: ${sz:fileSize(1024)} <!-- 1 K -->
Some Size: ${sz:fileSize(10485760)} <!-- 10 MB -->
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top