Android examples for java.io:File Size
format File Size
import android.text.*; import android.text.style.CharacterStyle; import android.text.style.ForegroundColorSpan; import java.text.DecimalFormat; public class Main{ public static String formatFileSize(long len) { return formatFileSize(len, false); }//from w ww .j a v a 2 s .c o m public static String formatFileSize(long len, boolean keepZero) { String size; DecimalFormat formatKeepTwoZero = new DecimalFormat("#.00"); DecimalFormat formatKeepOneZero = new DecimalFormat("#.0"); if (len < 1024) { size = String.valueOf(len + "B"); } else if (len < 10 * 1024) { size = String.valueOf(len * 100 / 1024 / (float) 100) + "KB"; } else if (len < 100 * 1024) { size = String.valueOf(len * 10 / 1024 / (float) 10) + "KB"; } else if (len < 1024 * 1024) { size = String.valueOf(len / 1024) + "KB"; } else if (len < 10 * 1024 * 1024) { if (keepZero) { size = String.valueOf(formatKeepTwoZero.format(len * 100 / 1024 / 1024 / (float) 100)) + "MB"; } else { size = String .valueOf(len * 100 / 1024 / 1024 / (float) 100) + "MB"; } } else if (len < 100 * 1024 * 1024) { if (keepZero) { size = String.valueOf(formatKeepOneZero.format(len * 10 / 1024 / 1024 / (float) 10)) + "MB"; } else { size = String.valueOf(len * 10 / 1024 / 1024 / (float) 10) + "MB"; } } else if (len < 1024 * 1024 * 1024) { size = String.valueOf(len / 1024 / 1024) + "MB"; } else { size = String.valueOf(len * 100 / 1024 / 1024 / 1024 / (float) 100) + "GB"; } return size; } }