3

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

Zoe
  • 27,060
  • 21
  • 118
  • 148
Habba
  • 1,179
  • 2
  • 13
  • 32
  • 2
    Gradle is backed by either Groovy or Kotlin/JVM (depending on your impelmentation), and both of those have access to the Java file I/O classes. So, create a `File` that points to the resource and use that to check its length. – CommonsWare Mar 28 '19 at 13:42
  • Any tips how? I can't find any tutorials for using Kotlin or Groovy in Gradle. – Habba Mar 28 '19 at 14:18
  • 1
    Assuming that you have not specifically elected to use Kotlin, your Gradle script *is* Groovy. Gradle is (in part) a DSL that can be used in either Groovy or Kotlin scripts. – CommonsWare Mar 28 '19 at 14:46

1 Answers1

2

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.

shizhen
  • 12,251
  • 9
  • 52
  • 88
  • Thanks, I just figured out that Tasks do not have a return value. So they need to be def as methods. Pretty straightforward after that. – Habba Mar 29 '19 at 09:38