build.gradle studio 中的 build.gradle 文件如何处理相对路径

How build.gradle file in android studio deal with relative path

我正在使用 android studio 4.0.1,我有一个名为 app 的 ndk 模块,它具有如下图所示的折叠结构。现在我在突出显示的 build.gradle 文件中添加了一个任务,我在其中放置:

task conanInstall {
    def buildDir = new File("src/main/cpp/native_lib.build")
    buildDir.mkdirs()
...
}

如您所见,build.gradle文件在app文件夹中,所以我指定路径为src/main/cpp/native_lib.build,相对于gradle文件,然而,这失败了,我需要使用 app/src/main/cpp/native_lib.build 来让它工作。这是为什么?

在我在 android 部分看到的同一个 gradle 文件中:

externalNativeBuild {
    cmake {
        path "src/main/cpp/CMakeLists.txt"
        version "3.17.0"
    }
}

那里的路径以 src 而不是 app 开头。这让我对 gradle 文件如何处理相对路径感到困惑。

java.io.File 解析当前用户目录的相对路径。 the doc 是这么说的:

By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.

要解析相对于当前项目的路径,您可以使用 file(...):

task conanInstall {
    def buildDir = file("src/main/cpp/native_lib.build")
    buildDir.mkdirs()
...
}

其中 file()org.gradle.api.Project#file(java.lang.Object),并且(根据 javadoc)它完全满足您的需要:

Resolves a file path relative to the project directory of this project.