Java 如何通过 Groovy 获取文件 build.gradle 的完整路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23522198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 23:34:13  来源:igfitidea点击:

How get full path to file build.gradle by Groovy?

javagroovypathgradle

提问by

I need create file in my java-project near buiid.gradle-file. I must create task (Groovy task) in build.gradle-file, my task must create file near buiid.gradle in my project, but I do not know - how do get path to buiid.gradle-file, that is putting in my project.

我需要在靠近 buiid.gradle 文件的 java 项目中创建文件。我必须在 build.gradle-file 中创建任务(Groovy 任务),我的任务必须在我的项目中的 buiid.gradle 附近创建文件,但我不知道 - 如何获取 buiid.gradle-file 的路径,这是放入我的项目。

How get full path to file buiid.gradle by Groovy? Help me, please.

如何通过 Groovy 获取文件 buiid.gradle 的完整路径?请帮帮我。

采纳答案by kuporific

There are several ways to accomplish this.

有几种方法可以实现这一点。

  1. If you look at the Working With Filespage, you can simply use the file()method that is a part of the Projectobject.
  2. If you look at the Project DSL Docs, you should see the projectDirproperty. Thes properties are available throughout the build.gradlescript.
  1. 如果您查看“使用文件”页面,您可以简单地使用file()作为Project对象一部分的方法。
  2. 如果您查看Project DSL Docs,您应该会看到该projectDir属性。这些属性在整个build.gradle脚本中都可用。

They can be used, respectively, like this:

它们可以分别使用,如下所示:

task myTask << {
    println file('.')
    println projectDir
}

Would output

会输出

/full/path/to/your/project/
/full/path/to/your/project/

Where that directory contains the build.gradlefile where the task is located.

该目录包含build.gradle任务所在的文件。

回答by Stephen Talley

To get a handle to the java.io.File that represents the currently-executing .gradle file:

要获取代表当前正在执行的 .gradle 文件的 java.io.File 的句柄:

def file = buildscript.sourceFile

In my case, I needed the directory of that script so I could apply other configuration from the same directory:

就我而言,我需要该脚本的目录,以便我可以从同一目录应用其他配置:

def buildCommonDir = buildscript.sourceFile.getParent()
apply from: "$buildCommonDir/common.gradle"

This approach works with any.gradle file, not just build.gradle.

这种方法适用于任何.gradle 文件,而不仅仅是 build.gradle。