说明
使用方法:
FileMemoryUtil.prettyByteSize(35871)
,参数为字节个数
返回结果:保留一位小数的自适应结果(例如:4.1KB)。可以留意在浏览器上下载的文件,会根据文件大小展示不同的单位(如下图),本工具类也可以实现。
扩展:可以自己控制需要保留的位数。
Java代码
/**
* 将文件大小B转为KB、MB、G、TB、PB
*/
public class FileMemoryUtil {
private static final int UNIT = 1024;
/**
* Convert bytes to a human-readable string
*
* @param byteSize byte size
* @return size of memory
*/
public static String prettyByteSize(long byteSize) {
double size = 1.0 * byteSize;
String type;
if ((int) Math.floor(size / UNIT) <= 0) {
//Less than 1KB
type = "B";
return format(size, type);
}
size = size / UNIT;
if<