How to convert byte size into human readable forma

2019-01-01 06:16发布

How to convert byte size into human-readable format in Java? Like 1024 should become "1 Kb" and 1024*1024 should become "1 Mb".

I am kind of sick of writing this utility method for each project. Are there any static methods in Apache Commons for this?

20条回答
与君花间醉酒
2楼-- · 2019-01-01 06:48

Use Android builtin Class

For Android there is a class Formatter. Just one like of code and you are done.

android.text.format.Formatter.formatShortFileSize(activityContext, bytes);

It is Like formatFileSize(), but trying to generate shorter numbers (showing fewer decimals).

android.text.format.Formatter.formatFileSize(activityContext, bytes);

Formats a content size to be in the form of bytes, kilobytes, megabytes, etc.

查看更多
梦寄多情
3楼-- · 2019-01-01 06:49

Maybe you can use this code(in C#):

        long Kb = 1024;
        long Mb = Kb * 1024;
        long Gb = Mb * 1024;
        long Tb = Gb * 1024;
        long Pb = Tb * 1024;
        long Eb = Pb * 1024;

        if (size < Kb) return size.ToString() + " byte";
        if (size < Mb) return (size / Kb).ToString("###.##") + " Kb.";
        if (size < Gb) return (size / Mb).ToString("###.##") + " Mb.";
        if (size < Tb) return (size / Gb).ToString("###.##") + " Gb.";
        if (size < Pb) return (size / Tb).ToString("###.##") + " Tb.";
        if (size < Eb) return (size / Pb).ToString("###.##") + " Pb.";
        if (size >= Eb) return (size / Eb).ToString("###.##") + " Eb.";

        return "invalid size";
查看更多
登录 后发表回答