Gradle(Kotlin DSL) でファイルダウンロードして解凍

blog1.mammb.com


任意ファイルのダウンロード

任意のファイルダウンロードは以下のように書くことができます。

val url = "https://path/to/file.zip";  
val file = layout.buildDirectory.file("file.zip")
uri(url).toURL().openStream().use {
  `java.nio.file`.Files.copy(it, file.asFile.toPath())
}

チャネルを使った場合は以下のようにできます。

Channels.newChannel(uri(url).toURL().openStream()).use { ch ->
    FileOutputStream(file.asFile).getChannel().use { fc ->
        fc.transferFrom(ch, 0, Long.MAX_VALUE)
    }
}

ant を使って以下のような書き方もあります。

    val dest = File("${project.projectDir}/example.jar")
    val url = "https://example.com/example.jar"
    if (!dest.exists()) ant.invokeMethod("get", mapOf("src" to url, "dest" to dest))


zip ファイルの解凍

zip ファイルの解凍は、Copy タスクで以下のように実行できます。

tasks.register<Copy>("unzip") {
    val zip = layout.buildDirectory.file("file.zip")
    from(zipTree(zip))
    into(layout.projectDirectory.dir("out"))
}


ダウンロードして解凍

ダウンロードと解凍を合わせると以下のように書けます。

tasks.register<Copy>("download") {

    val url = "https://path/to/file.zip";
    val zip = layout.buildDirectory.file("file.zip")
    val out = layout.buildDirectory.dir("out")

    zip.get().also { if (!it.asFile.exists()) 
        uri(url).toURL().openStream().use {
            str -> `java.nio.file.`Files.copy(str, zip.get().asFile.toPath())
        }
    }

    from(zipTree(zip))
    into(out)
}

zip ファイルが存在する場合は、ダウンロードはスキップします。