2009-04-29 8 views
4

Je me demandais si quelqu'un connaissait un bon moyen de formater les tailles de fichiers dans les pages Java/JSP/JSTL.Formatage des tailles de fichier en Java/JSTL

Existe-t-il une classe util avec cela?
J'ai recherché des communs mais je n'ai rien trouvé. Des balises personnalisées?
Est-ce qu'une bibliothèque existe déjà pour cela?

Idéalement, je voudrais à se comporter comme le -h interrupteur sur ls Unix commande

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

Répondre

6

Une recherche rapide sur google m'a renvoyé this du projet Appache Hadoop. Copie à partir de là: (Apache License, Version 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; 
    } 

Il utilise 1K = 1024, mais vous pouvez adapter si vous préférez. Vous devez également gérer le cas < 1024 avec un DecimalFormat différent.

+0

voir http://stackoverflow.com/ questions/3758606/comment convertir-byte-size-en-human-readable-format-in-java pour une solution plus propre – Niko

5

Vous pouvez utiliser les méthodes commons-io FileUtils.byteCountToDisplaySize. Pour une mise en œuvre JSTL vous pouvez ajouter la fonction taglib suivante tout en ayant commons-io sur votre classpath:

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

maintenant dans votre JSP vous pouvez faire:

<%@ taglib uri="/WEB-INF/FileSizeFormatter.tld" prefix="sz"%> 
Some Size: ${sz:fileSize(1024)} <!-- 1 K --> 
Some Size: ${sz:fileSize(10485760)} <!-- 10 MB --> 
Questions connexes