3

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?

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If I wanted to exclude files in a directory, how would I do that?
@Amir - I added a note on exclusions.
4

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.