Amir Afghani
Amir Afghani

Reputation: 38531

Ant script with embedded javascript trying to read files

I have the following ant build target :

<target name="analyze">
    <script language="javascript">
    <![CDATA[
            importPackage(java.lang);
            var path = project.getProperty("PROJECT_HOME") + "/oms";
            System.out.println("path = " +path);                
        ]]>
    ]]>
    </script>
</target>

I'd like to find all files in the directory recursively and if they end in .java print them out. Is this possible?

Upvotes: 3

Views: 6709

Answers (2)

martin clayton
martin clayton

Reputation: 78115

There is an example in the Ant script task docs that basically does this. Here's a simplified version:

<script language="javascript">
<![CDATA[
    importClass(java.io.File);

    fs = project.createDataType("fileset");
    dir = "src";
    fs.setDir( new File( dir ) );
    fs.setIncludes( "**/*.java" );

    // create echo Task via Ant API
    echo = project.createTask("echo");

    // iterate over files found.
    srcFiles = fs.getDirectoryScanner( project ).getIncludedFiles( );
    for ( i = 0; i < srcFiles.length; i++ ) {
        var filename = srcFiles[i];

        // use echo Task via Ant API
        echo.setMessage( filename );
        echo.perform( );
    }]]>
</script>

This uses an Ant FileSet to find the files. Here an includes rule is set on the fileset so that only .java files found are returned by the iterator - saves using string operations on the filenames to discard any other files.

If you need to set exclusion rules you can do so by means of the setExcludes() method of the FileSet class (actually of the AbstractFileset class). See the docs for patterns to understand a little more about Ant wildcards.

Upvotes: 10

ewan.chalmers
ewan.chalmers

Reputation: 16235

You could also do this with core Ant tasks, without using javascript:

  <fileset dir="java" id="java.files.ref">
    <include name="**/*.java"/>
  </fileset>
  <pathconvert pathsep="${line.separator}" property="java.files" refid="java.files.ref"/>
  <echo>${java.files}</echo>

Upvotes: 4

Related Questions