这取决于您的操作系统,例如Unix 不存储文件创建时间,see details here
两种可能的解决方案:
解决方案 1,仅适用于 Java >= 6 的 Windows,无需插件
<project>
<!-- Works on Windows only, uses the jdk builtin
rhino javascript engine (since jdk6)
use dir command without /T:C to get lastmodificationtime
-->
<macrodef name="getFileTimes">
<attribute name="dir" />
<attribute name="file" />
<attribute name="setprop" default="@{file}_ctime" />
<sequential>
<exec executable="cmd" dir="@{dir}" outputproperty="@{setprop}">
<arg value="/c" />
<arg line="dir @{file} /T:C|find ' @{file}'" />
</exec>
<script language="javascript">
tmp = project.getProperty("@{setprop}").split("\\s+") ;
project.setProperty("@{setprop}", tmp[0] + "/" + tmp[1]) ;
</script>
</sequential>
</macrodef>
<getFileTimes dir="C:/tmp" file="bookmarks.html" />
<echo>
$${bookmarks.html_ctime} => ${bookmarks.html_ctime}
</echo>
</project>
解决方案 2,需要 Java 7 和 groovy-all-x.x.x.jar(包含在 groovy binary release 中)
根据自己的喜好调整 SimpleDateFormat。
在 Unix 文件系统上,当询问创建时间时,您将获得最后修改时间。
<project>
<taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy"/>
<!-- Solution for Java 7, uses the nio package
needs groovy-all-2.1.0.jar
-->
<macrodef name="getFileTimes">
<attribute name="file"/>
<attribute name="ctimeprop" default="@{file}_ctime"/>
<attribute name="mtimeprop" default="@{file}_mtime"/>
<sequential>
<groovy>
import java.nio.file.*
import java.nio.file.attribute.*
import java.text.*
import java.util.date.*
Path path = Paths.get("@{file}")
BasicFileAttributeView view = Files.getFileAttributeView(path, BasicFileAttributeView.class)
BasicFileAttributes attributes = view.readAttributes()
lastModifiedTime = attributes.lastModifiedTime()
createTime = attributes.creationTime()
DateFormat df = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss", Locale.US)
df.format(new Date(createTime.toMillis()))
properties.'@{ctimeprop}' = df.format(new Date(createTime.toMillis()))
properties.'@{mtimeprop}' = df.format(new Date(lastModifiedTime.toMillis()))
</groovy>
</sequential>
</macrodef>
<getFileTimes file="C:/tmp/bookmarks.html"/>
<echo>
$${C:/tmp/bookmarks.html_ctime} => ${C:/tmp/bookmarks.html_ctime}
$${C:/tmp/bookmarks.html_mtime} => ${C:/tmp/bookmarks.html_mtime}
</echo>
</project>
我也尝试使用内置的 javascript 引擎,但出现如下错误:
sun.org.mozilla.javascript.internal.EvaluatorException: missing name after . operator
IMO,对于简单的事情,使用 javascript <script language="javascript"> 就足够了,但如果你需要导入 java 包等......它是一个 PITA。 Groovy 很简单。