将文件的大小以最合适的单位显示

package com.lll.mgr;

import java.text.DecimalFormat;

/**
 * 工具类 。
 */
public class Util {

	/**
	 * 获取带单位的文件名,单位会自动显示为合适的值,如B、KB、MB等
	 * @param size 文件字节大小
	 */
	public static String readableFileSize(long size) {
		if(size <= 0) return "0";
	    final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
	    int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
	    return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
	}
	public static void main(String[] args) {
		System.out.println(Util.readableFileSize(1024));
	}
}


猜你喜欢

转载自blog.csdn.net/zhang854429783/article/details/45345547
今日推荐