2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

how to convert byte to KB or MB or GB etc in java

how to convert byte to KB or MB or GB etc in java.

basically i have a file which i want to show user as KB or MB or GB etc...

Now my problem is to convert byte length to expected type in java. Can anybody have good solution for it.

userimage

You can use below code to convert:


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];
    }

Answer is