Pergunta

Esta questão já tem uma resposta aqui:

Eu queria saber se alguém sabia de uma boa maneira de tamanhos de arquivos de formato em páginas Java / JSP / JSTL.

Existe uma classe util que com isso?
Eu procurei commons, mas não encontrou nada. Quaisquer marcas personalizadas
Será uma biblioteca já existem para isso?

Idealmente, eu gostaria que ele se comporte como o -h ligar do Unix ls comando

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

Foi útil?

Solução

Uma busca rápida no google me retornou este do projeto appache Hadoop. Copiar a partir daí: (Apache License, Versão 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;
  }

Ele usa 1K = 1024, mas você pode adaptar este se você preferir. Você também precisa lidar com o <1024 caso com um DecimalFormat diferente.

Outras dicas

Você pode usar os métodos FileUtils.byteCountToDisplaySize commons-io. Para uma implementação JSTL você pode adicionar a seguinte função taglib ao ter commons-io em seu classpath:

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

Agora, em sua JSP você pode fazer:

<%@ taglib uri="/WEB-INF/FileSizeFormatter.tld" prefix="sz"%>
Some Size: ${sz:fileSize(1024)} <!-- 1 K -->
Some Size: ${sz:fileSize(10485760)} <!-- 10 MB -->
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top