This commit is contained in:
Looly 2024-09-08 03:18:39 +08:00
parent 91d4989c16
commit 10d84af86a
3 changed files with 36 additions and 6 deletions

View File

@ -16,6 +16,8 @@
package org.dromara.hutool.core.io.unit;
import org.dromara.hutool.core.text.StrUtil;
import java.text.DecimalFormat;
/**
@ -44,11 +46,37 @@ public class DataSizeUtil {
* @return 大小
*/
public static String format(final long size) {
return format(size, false);
}
/**
* 可读的文件大小<br>
* 参考 <a href="http://stackoverflow.com/questions/3263892/format-file-size-as-mb-gb-etc">http://stackoverflow.com/questions/3263892/format-file-size-as-mb-gb-etc</a>
*
* @param size Long类型大小
* @param useSimpleName 是否使用简写例如1KB 简写成 1K
* @return 大小
*/
public static String format(final long size, final boolean useSimpleName) {
return format(size, 2, useSimpleName ? DataUnit.UNIT_NAMES_SIMPLE : DataUnit.UNIT_NAMES, StrUtil.SPACE);
}
/**
* 可读的文件大小<br>
* 参考 <a href="http://stackoverflow.com/questions/3263892/format-file-size-as-mb-gb-etc">http://stackoverflow.com/questions/3263892/format-file-size-as-mb-gb-etc</a>
*
* @param size Long类型大小
* @param scale 小数点位数四舍五入
* @param unitNames 单位数组
* @param delimiter 数字和单位的分隔符
* @return 大小
*/
public static String format(final long size, final int scale, final String[] unitNames, final String delimiter) {
if (size <= 0) {
return "0";
}
final int digitGroups = Math.min(DataUnit.UNIT_NAMES.length-1, (int) (Math.log10(size) / Math.log10(1024)));
return new DecimalFormat("#,##0.##")
.format(size / Math.pow(1024, digitGroups)) + " " + DataUnit.UNIT_NAMES[digitGroups];
final int digitGroups = Math.min(unitNames.length - 1, (int) (Math.log10(size) / Math.log10(1024)));
return new DecimalFormat("#,##0." + StrUtil.repeat('#', scale))
.format(size / Math.pow(1024, digitGroups)) + delimiter + unitNames[digitGroups];
}
}

View File

@ -64,6 +64,10 @@ public enum DataUnit {
* 单位名称列表
*/
public static final String[] UNIT_NAMES = new String[]{"B", "KB", "MB", "GB", "TB", "PB", "EB"};
/**
* 单位名称列表简写
*/
public static final String[] UNIT_NAMES_SIMPLE = new String[]{"B", "K", "M", "G", "T", "P", "E"};
private final String suffix;

View File

@ -21,15 +21,13 @@ import org.dromara.hutool.core.text.replacer.ReplacerChain;
/**
* XML特殊字符转义<br>
* <a href="https://stackoverflow.com/questions/1091945/what-characters-do-i-need-to-escape-in-xml-documents">
* https://stackoverflow.com/questions/1091945/what-characters-do-i-need-to-escape-in-xml-documents</a><br>
* https://stackoverflow.com/questions/1091945/what-characters-do-i-need-to-escape-in-xml-documents<br>
*
* <pre>
* &amp; (ampersand) 替换为 &amp;amp;
* &lt; (less than) 替换为 &amp;lt;
* &gt; (greater than) 替换为 &amp;gt;
* &quot; (double quote) 替换为 &amp;quot;
* ' (single quote / apostrophe) 替换为 &amp;apos;
* </pre>
*
* @author looly