问题描述
仅使用本机 ANT 任务,如何创建自定义 ANT 任务以执行以下操作:
Using only native ANT tasks, how can I create a custom ANT task to do the following:
- 计算自当地时间 2000 年 1 月 1 日以来的天数并将其存储在属性中.
- 计算自当地时间午夜开始的秒数,除以 2 并将其存储在属性中.
然后将上述属性值附加到其他属性值并写入文件.
The above property values will then be appended to others and written to a file.
推荐答案
ANT 不是通用编程语言,因此您需要编写自定义任务或使用类似 groovy 插件
ANT is not a general purpose programming language, so you need to write a custom task or alternatively use something like the groovy plugin
以下示例演示了使用 Joda Time 库的 groovy 任务如何将属性设置为您已指定.
The following example demonstrates how a groovy task using the Joda Time library can set the properties as you've specified.
<taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy" classpathref="build.path"/>
<groovy>
import org.joda.time.*
def now = new DateTime()
def midnight = new DateMidnight()
def year2000 = new DateTime(2000,1,1,0,0,0,0)
properties["year2000.days"] = Days.daysBetween(year2000, now).days
properties["midnight.seconds"] = Seconds.secondsBetween(midnight, now).seconds
properties["midnight.seconds.halved"] = Seconds.secondsBetween(midnight, now).dividedBy(2).seconds
</groovy>
我不能高度推荐 Joda Time,Java 中的标准日期和时间操作简直糟透了!
I can't recommend Joda Time highly enough, standard Date and Time manipulation in Java just sucks!
上面的 groovy 任务将需要您的类路径中的以下 jars:
The groovy task above will require the following jars on your classpath:
- groovy-all-1.7.4.jar
- joda-time-1.6.1.jar
我建议使用 ivy 插件来管理这些,方法是添加一个解析"目标来下载 jar 并自动设置类路径:
I'd recommend using the ivy plugin to manage these by adding a "resolve" target that downloads the jars and sets the classpath automatically:
<target name="resolve">
<ivy:resolve/>
<ivy:cachepath pathid="build.path"/>
</target>
以下是ivy.xml,其中列出了要下载的依赖项:
The following is the ivy.xml that lists the dependencies to be downloaded:
<ivy-module version="2.0">
<info organisation="org.myspotontheweb" module="demo"/>
<dependencies>
<dependency org="org.codehaus.groovy" name="groovy-all" rev="1.7.4" conf="default"/>
<dependency org="joda-time" name="joda-time" rev="1.6.1" conf="default"/>
</dependencies>
</ivy-module>
这篇关于使用原生 Ant 任务执行简单计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!