在Java / JSTL中格式化文件大小 [英] Formatting file sizes in Java/JSTL
问题描述
有没有这样做的util类?
我搜遍了commons但什么也没找到。任何自定义标签?
这个库是否已经存在?
理想情况下,我希望它的行为像 -h 打开Unix的 ls 命令
34 - > 34
795 - > 795
2646 - > 2.6K
2705 - > 2.7K
4096 - > 4.0K
13588 - > 14K
28282471 - > 27M
28533748 - > 28M
快速的谷歌搜索返回给我这个从Appache hadoop项目。从那里复制:
(Apache许可证,版本2.0):
private static DecimalFormat oneDecimal = new DecimalFormat(0.0 );
/ **
*给定一个整数,返回一个近似值,但是人类
*可读格式的字符串。
* 1024,1024 ** 2和1024 ** 3使用基数'k','m'和'g'。
* @param数字格式的数字
* @return一个人类可读的整数形式
* /
public static String humanReadableInt(long number){
long absNumber = Math.abs(number);
double result = number;
字符串后缀=; (absNumber <1024){
// nothing
} else if(absNumber <1024 * 1024){
result = number / 1024.0;
后缀=k;
} else if(absNumber <1024 * 1024 * 1024){
result = number /(1024.0 * 1024);
后缀=m;
} else {
result = number /(1024.0 * 1024 * 1024);
后缀=g;
}
返回oneDecimal.format(结果)+后缀;
$ / code $ / pre
$ b $ p它使用1K = 1024,但是如果你愿意的话,你可以调整它。您还需要使用不同的DecimalFormat处理< 1024个案例。
I was wondering if anyone knew of a good way to format files sizes in Java/JSP/JSTL pages.
Is there a util class that with do this?
I've searched commons but found nothing. Any custom tags?
Does a library already exist for this?
Ideally I'd like it to behave like the -h switch on Unix's ls command
34 -> 34
795 -> 795
2646 -> 2.6K
2705 -> 2.7K
4096 -> 4.0K
13588 -> 14K
28282471 -> 27M
28533748 -> 28M
解决方案 A quick google search returned me this from Appache hadoop project. Copying from there:
(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;
}
It uses 1K = 1024, but you can adapt this if you prefer. You also need to handle the <1024 case with a different DecimalFormat.
这篇关于在Java / JSTL中格式化文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!