/** * 格式化字节数据 * * @param size 大小,单位字节 */ public static String formatSize(Long size) { if (size == null || size <= 0) { return ""; } String[] units = {"B", "KB", "MB", "GB", "TB"}; int unitIndex = (int) (Math.log10(size) / 3); double unitValue = 1 << (unitIndex * 10); return BigDecimal.valueOf(size / unitValue).setScale(2, RoundingMode.HALF_UP) + " " + units[unitIndex]; }
使用
public static void main(String[] args) { System.out.println(formatSize(3141366L)); }
结果 (单位和数字之间会有一个空格)
3.00 MB
标签:文件大小,格式化,字节,String,static,JAVA,size From: https://www.cnblogs.com/pxblog/p/18047321