0

Is there a way to detect the properties of a file using ant. For example: date created, date modified, size, etc...? I can't find anything built in that allows me to do that. Thanks

tony
  • 823
  • 2
  • 16
  • 25

1 Answers1

1

Correct, nothing built in.

The following example uses the groovy ant task to call the Java NIO libraries:

<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>

Update

Run the following commands to install the groovy task jar into a location that ANT can use:

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

Additionally, I'm using ANT 1.9.4 and Java 1.7.0_25

Mark O'Connor
  • 76,015
  • 10
  • 139
  • 185
  • Thanks for the code. I am trying to tst the code but I am getting an error: groovy.lang.MissingPropertyException: No such property: Paths for class: embedded_ script_in_c__Builds_ant_script_test_ant_dot_xml at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50) Sorry but I don't know groovy – tony Nov 21 '14 at 17:05
  • @tony Updated my answer with instructions on how to install latest version of groovy ant task. – Mark O'Connor Nov 21 '14 at 21:00