how do I get file size of temp file in android?

前端 未结 3 1159
一整个雨季
一整个雨季 2020-12-02 17:55

if I use openFileOutput() to create and write to a temp file how do I get filesize after I\'m done writing to it?

3条回答
  •  悲哀的现实
    2020-12-02 18:41

    Kotlin Extension Solution

    Add these somewhere, then call myFile.sizeInMb or whichever you need

    val File.size get() = if (!exists()) 0.0 else length().toDouble()
    val File.sizeInKb get() = size / 1024
    val File.sizeInMb get() = sizeInKb / 1024
    val File.sizeInGb get() = sizeInMb / 1024
    val File.sizeInTb get() = sizeInGb / 1024
    

    If you need a File from a String or Uri, try adding these

    fun Uri.asFile(): File = File(toString())
    
    fun String?.asUri(): Uri? {
        try {
            return Uri.parse(this)
        } catch (e: Exception) {
        }
        return null
    }
    

    If you'd like to easily display the values as a string, these are simple wrappers. Feel free to customize the default decimals displayed

    fun File.sizeStr(): String = size.toString()
    fun File.sizeStrInKb(decimals: Int = 0): String = "%.${decimals}f".format(sizeInKb)
    fun File.sizeStrInMb(decimals: Int = 0): String = "%.${decimals}f".format(sizeInMb)
    fun File.sizeStrInGb(decimals: Int = 0): String = "%.${decimals}f".format(sizeInGb)
    
    fun File.sizeStrWithBytes(): String = sizeStr() + "b"
    fun File.sizeStrWithKb(decimals: Int = 0): String = sizeStrInKb(decimals) + "Kb"
    fun File.sizeStrWithMb(decimals: Int = 0): String = sizeStrInMb(decimals) + "Mb"
    fun File.sizeStrWithGb(decimals: Int = 0): String = sizeStrInGb(decimals) + "Gb"
    

提交回复
热议问题