how to convert byte size into human readable format in java

Converting Byte Size into Human Readable Format in Kotlin

To convert a byte size into a human-readable format in Kotlin, you can use the following function:

fun formatByteSize(bytes: Long): String {
    val units = arrayOf("B", "KB", "MB", "GB", "TB")
    var size = bytes.toDouble()
    var unit = 0
    while (size >= 1024 && unit < units.size - 1) {
        size /= 1024
        unit++
    }
    return "%.2f %s".format(size, units[unit])
}

Let's break down the steps involved in this function:

  1. The function formatByteSize takes a bytes parameter of type Long representing the byte size to be converted.

  2. An array units is defined, which contains the units of measurement for byte sizes (e.g., B, KB, MB, GB, TB).

  3. The variable size is initialized with the value of bytes converted to a Double.

  4. The variable unit is initialized to 0, representing the index of the unit in the units array.

  5. A while loop is used to divide the size by 1024 as long as size is greater than or equal to 1024 and unit is less than the index of the last unit in the units array. This loop allows us to determine the appropriate unit for the byte size.

  6. Inside the loop, size is divided by 1024 and unit is incremented.

  7. Finally, the function returns a formatted string using the size and unit values. The %.2f format specifier is used to format the size with two decimal places, and the corresponding unit from the units array is appended.

Here's an example usage of the formatByteSize function:

val byteSize = 128974848L
val formattedSize = formatByteSize(byteSize)
println("Formatted Size: $formattedSize")

Output:

Formatted Size: 122.93 MB

This function allows you to convert a byte size into a human-readable format, making it easier to understand and display byte sizes in a more user-friendly way.

[[SOURCE 1]]