format File Size till GB - Android java.io

Android examples for java.io:File Size

Description

format File Size till GB

Demo Code

import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
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  av  a2 s  .com

    private static String formatFileSize(long len, boolean keepZero) {
        // TODO Auto-generated method stub
        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 * 100 / 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(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;
    }

}

Related Tutorials