androidgradleandroid-gradle-pluginapk-expansion-files

How do I read file size with Gradle?


Short version:

How do I read a file's size in bytes with Gradle?

Long version:

My Android build scripts I use with Android Studio need to figure out the size of a resource file in bytes. I'd like that my scripts would do it automatically. How would I do it?

Edit: Added code that I have now:

task getFileSizeFromObb {
    doLast {
        File mainObb = new File("data-android.obb")
        return mainObb.length()
    }
}


android {

    defaultConfig {
        //...
        manifestPlaceholders = [main_obb_size: getFileSizeFromObb.execute()]
        //...
    }
}

This fails with

ERROR: Cause: null value in entry: main_obb_size=null


Solution

  • Try below code to define a gradle/groovy method that returns your file size.

    def getFileSizeFromObb() {
        File mainObb = new File("data-android.obb")
        return mainObb.length()
    }
    

    and call this method like below:

    android {
    
        defaultConfig {
            //...
            println "===++++ >>>>> size = " + getFileSizeFromObb()
            manifestPlaceholders = [main_obb_size: getFileSizeFromObb()]
            //...
        }
    }
    
    

    I have verified above method, please ensure that your file data-android.obb does exist on the path.