tony
tony

Reputation: 853

Ant: how to detect the properties of a file

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

Upvotes: 0

Views: 90

Answers (1)

Mark O'Connor
Mark O'Connor

Reputation: 78021

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

Upvotes: 1

Related Questions