【问题标题】:Ant: how to detect the properties of a fileAnt:如何检测文件的属性
【发布时间】:2014-11-19 20:04:18
【问题描述】:

有没有办法使用 ant 来检测文件的属性。 例如:创建日期、修改日期、大小等...? 我找不到任何内置的东西可以让我这样做。 谢谢

【问题讨论】:

标签: ant


【解决方案1】:

正确,没有内置任何东西。

以下示例使用groovy ant task 调用Java NIO 库:

<project name="demo" default="build">

  <taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy"/>

  <macrodef name="getMetadata">
    <attribute name="file"/>
    <sequential>
      <groovy>
      import java.nio.file.*
      import java.nio.file.attribute.*
      import java.text.*

      def path = Paths.get("@{file}")

      def attributes = Files.getFileAttributeView(path, BasicFileAttributeView.class).readAttributes()
      def df = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss", Locale.US)

      properties.'@{file}_size'  = attributes.size()
      properties.'@{file}_ctime' = df.format(new Date(attributes.creationTime().toMillis()))
      properties.'@{file}_mtime' = df.format(new Date(attributes.lastModifiedTime().toMillis()))
      properties.'@{file}_atime' = df.format(new Date(attributes.lastAccessTime().toMillis()))
     </groovy>
    </sequential>
  </macrodef>

  <target name="build">
    <getMetadata file="src/foo/bar/A.txt"/>

    <echo message="File            : src/foo/bar/A.txt"/>
    <echo message="Size            : ${src/foo/bar/A.txt_size}"/>
    <echo message="Create time     : ${src/foo/bar/A.txt_ctime}"/>
    <echo message="Modified time   : ${src/foo/bar/A.txt_mtime}"/>
    <echo message="Last access time: ${src/foo/bar/A.txt_atime}"/>
  </target>

</project>

更新

运行以下命令将 groovy 任务 jar 安装到 ANT 可以使用的位置:

mkdir -p ~/.ant/lib
curl http://search.maven.org/remotecontent?filepath=org/codehaus/groovy/groovy-all/2.3.7/groovy-all-2.3.7.jar -L -o ~/.ant/lib/groovy-all.jar

另外,我使用的是 ANT 1.9.4 和 Java 1.7.0_25

【讨论】:

  • 感谢您的代码。我正在尝试测试代码,但出现错误:groovy.lang.MissingPropertyException:没有这样的属性:类的路径:org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50) 上的 Embedded_script_in_c__Builds_ant_script_test_ant_dot_xml但我不知道 groovy
  • @tony 用如何安装最新版本的 groovy ant 任务的说明更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 2011-08-05
  • 2016-09-08
  • 1970-01-01
  • 2011-09-10
  • 1970-01-01
  • 2014-10-29
  • 1970-01-01
  • 2011-05-09
相关资源
最近更新 更多