Here you can find the source of formatFilesize(long filesize)
Parameter | Description |
---|---|
filesize | in bytes |
public static String formatFilesize(long filesize)
//package com.java2s; // it under the terms of the GNU General Public License as published by import java.text.NumberFormat; public class Main { /** static number format instance. Used to format filesizes. */ private static NumberFormat numberFormat = NumberFormat.getInstance(); /** Formats filesize in bytes as appropriate to Bytes, KB, MB or GB */*from w ww. j ava2 s. co m*/ * @param filesize in bytes * @return formatted filesize **/ public static String formatFilesize(long filesize) { String result; if (Math.abs(filesize) < 1024) { result = "" + filesize + " Bytes"; } else if (Math.abs(filesize) < 1048576) { result = formatFilesizeKB(filesize, 2); } else if (Math.abs(filesize) < 1073741824) { result = formatFilesizeMB(filesize, 2); } else { result = formatFilesizeGB(filesize, 2); } return result; } /** Formats filesize in bytes to KB * * @param filesize in bytes * @param fractionDigits ... * @return formatted filesize */ private static String formatFilesizeKB(long filesize, int fractionDigits) { numberFormat.setMaximumFractionDigits(fractionDigits); return new StringBuffer(numberFormat.format(filesize / 1024.0)).append(" KB").toString(); } /** Formats filesize in bytes to KB * * @param filesize in bytes * @return formatted filesize */ public static String formatFilesizeKB(long filesize) { return new StringBuffer().append(filesize / 1024).append(" KB").toString(); } /** Formats filesize in bytes to MB * * @param filesize in bytes * @param fractionDigits ... * @return formatted filesize */ private static String formatFilesizeMB(long filesize, int fractionDigits) { numberFormat.setMaximumFractionDigits(fractionDigits); // 1048576 = 1024.0 * 1024.0 return new StringBuffer(numberFormat.format(filesize / 1048576.0)).append(" MB").toString(); } /** Formats filesize in bytes to GB * * @param filesize in bytes * @param fractionDigits ... * @return formatted filesize */ private static String formatFilesizeGB(long filesize, int fractionDigits) { numberFormat.setMaximumFractionDigits(fractionDigits); // 1048576 = 1024.0 * 1024.0 return new StringBuffer(numberFormat.format(filesize / 1073741824.0)).append(" GB").toString(); } }