Search code examples
antsizedirectorywritefilefile-listing

Write folder name and their sizes in a file using Ant


I need some help with Ant. I want to create a file using Ant, which to contain some names and the size in kb of some folders and also to contain other kind of data(not size) but with the same pattern. Something like this:

build.date=April 01, 2000
folder1=10000
folder2=59093
folder3=646854
folder4=14897123

And also to make the sum of some folder sizes(for example foldersum=folder1+folder2) and write that in the file:

build.date=April 01, 2000
folder1=10000
folder2=59093
folder3=646854
folder4=14897123
foldersum=folder1+folder2

Solution

  • ANT is not a programming language. The best way to do this is to embed a scripting language, for example groovy.

    Example

    Given the following directory structure

    ├── build.xml
    ├── folder1
    │   ├── file1.txt
    │   ├── file2.txt
    │   └── file3.txt
    ├── folder2
    │   ├── file4.txt
    │   └── file5.txt
    └── folder3
        └── file6.txt
    

    Produces a file called "build-report.txt"

    build.date=April 09,2015
    folder1=1
    folder2=1
    folder3=1
    foldersum=3
    

    build.xml

    <project name="demo" default="build">
    
      <available classname="org.codehaus.groovy.ant.Groovy" property="groovy.installed"/>
    
      <target name="build" depends="init">
        <taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy"/>
    
        <dirset id="dirs" dir="." includes="folder*"/>
    
        <groovy>
          import java.text.SimpleDateFormat
    
          def sdf = new SimpleDateFormat("MMMM dd,yyyy")
    
          new File("build-report.txt").withWriter { w ->
    
            w.println "build.date=${sdf.format(new Date())}"
    
            def total = 0
    
            ant.project.references.dirs.each {
              def dir = new File(it.toString())
              def size = dir.directorySize()
    
              w.println "${dir.name}=${size}"
    
              total += size
            }
    
            w.println "foldersum=${total}"
          }
        </groovy>
      </target>
    
      <target name="init" unless="groovy.installed">
        <mkdir dir="${user.home}/.ant/lib"/>
        <get dest="${user.home}/.ant/lib/groovy.jar" src="http://search.maven.org/remotecontent?filepath=org/codehaus/groovy/groovy-all/2.4.3/groovy-all-2.4.3.jar"/>
        <fail message="Groovy installed run build again"/>
      </target>
    
    </project>