You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Gradle脚本中获取解压后AAR的缓存路径以实现文件迁移

Gradle从AAR缓存中提取指定文件的解决方案

你遇到的报错核心原因是直接将未解压的AAR压缩包对象传入了Copy任务的from()方法,Copy任务默认不会自动解压压缩包读取内部文件,需要显式指定解压逻辑或直接使用已解压的缓存文件路径。

以下是两种可直接使用的解决方案:

方案1:直接从AAR压缩包提取文件(更稳定,不依赖缓存路径规则)

该方案不需要适配Gradle版本的缓存路径规则,直接从下载的AAR原始包中提取目标文件,兼容性更强:

// 替换为你目标AAR的实际依赖坐标
def targetAarCoord = "com.example:your-aar-lib:1.0.0"
// 替换为目标文件在AAR内部的完整路径
def targetFileInAar = "path/to/folder/file.conf"
// 替换为项目内的目标存放路径
def targetOutputPath = "${project.rootDir.path}/path/to/folder/"

tasks.register('moveFile', Copy) {
    // 解析依赖找到对应AAR文件,通过zipTree解压读取内部文件
    from zipTree(configurations.runtimeClasspath.files { 
        def coordParts = targetAarCoord.split(':')
        it.group == coordParts[0] 
        && it.name == coordParts[1] 
        && it.version == coordParts[2]
    }.single()) {
        // 仅保留目标文件,过滤AAR内其他无关文件
        include targetFileInAar
        // 可选配置:不需要保留AAR内的目录结构,直接把文件提取到目标根目录可打开下面注释
        // eachFile { it.path = it.name }
    }
    into targetOutputPath
    // 可选配置:自动挂接到构建流程,每次构建前自动执行
    // tasks.named("preBuild").configure { it.dependsOn this }
}

如果你的AAR是指定variant引入的(比如debugImplementation),把runtimeClasspath替换为对应variant的配置名即可,比如debugRuntimeClasspath。

方案2:读取transforms-2缓存中已解压的文件

如果需要直接使用Gradle已经解压完成的缓存文件,可以通过Android构建组件的Artifact接口查询解压路径:

// 替换为你目标AAR的实际依赖坐标
def targetAarCoord = "com.example:your-aar-lib:1.0.0"
// 替换为目标文件在解压后AAR目录中的相对路径
def targetFileInCache = "path/to/folder/file.conf"
// 替换为项目内的目标存放路径
def targetOutputPath = "${project.rootDir.path}/path/to/folder/"

tasks.register('moveFile', Copy) {
    from {
        // 查询AAR的解压后缓存路径
        def aarUnzipDirs = project.extensions.getByType(com.android.build.gradle.BaseExtension).artifactCollection
            .matching { it.coordinates == targetAarCoord }
            .artifacts
            .collect { it.file }
        // 拼接得到目标文件的完整缓存路径
        aarUnzipDirs.collect { new File(it, targetFileInCache) }
    }
    into targetOutputPath
}

内容的提问来源于stack exchange,提问作者Salocin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 22:57:03