Java字节单位转换和humanreadable工具
使用场景
系统中有很多字节单位单位转换,比如B->M,M->G等,而且有场景使用类似ll -h
这种操作,把一个字节单位转换为可读的显示方式,比如1024B->1M。
受com.google.guava:guava
包中的CaseFormat
类的启发,决定写一个ByteUnitFormat
类,专门用于转换字节单位或生成可读的字节单位。
代码
使用方法
public static void main(String[] args) {
System.out.println(B.to(K, 1024L, ByteUnitFormat.Rate.SI));
System.out.println(B.to(K, 1024L, ByteUnitFormat.Rate.IEC));
System.out.println(M.to(G, 4096L, ByteUnitFormat.Rate.IEC));
System.out.println(M.to(G, 4096L));
System.out.println(B.humanReadable(174541987L));
System.out.println(M.humanReadable(1024L));
}
/**
* 1.02K
* 1K
* 4G
* 4G
* 166.5M
* 1G
*/
其它
SI
:国际单位制(法语:Système International d’Unités 符号:SI),进率1000;
IEC
:国际电工委员会单位制,进率1024。