marc esher
marc esher

Reputation: 4921

How can I use Java in an Ant buildfile?

I'm trying to write a custom scriptselector, and to do so I need to read the contents of each file.

Is there a way to use java, and not javascript, as the language of a scriptselector? If not, is there a way, silly as it sounds, to read the File object?

<scriptselector language="javascript">
    f = self.getFile();
    println(f);
    //how to read the File?
    self.setSelected(true);
</scriptselector>

Upvotes: 6

Views: 1861

Answers (2)

marc esher
marc esher

Reputation: 4921

Here's how. Something along the lines of:

<scriptselector language="javascript">
    importPackage(java.io);
    importPackage(org.apache.tools.ant.util);

    fileUtils = FileUtils.getFileUtils();
    f = self.getFile();
    println(f);
    if( f.getAbsolutePath().endsWith(".xyz") ){
        fis = new FileInputStream(f.getAbsolutePath());
        isr = new InputStreamReader(fis);
        println('reading it!');
        fileContents = fileUtils.readFully(isr);
        println(fileContents);
        self.setSelected(true);
    }
</scriptselector>

Upvotes: 5

Dave L.
Dave L.

Reputation: 11238

You should be able to use any BSF-supported language, which includes BeanShell (Java). For example:

<script language="beanshell">
    String file = "foo.txt";
    InputStream is = null;
    try {
        is = new FileInputStream(file);
        // read from stream as required
    } finally {
        if (is != null) {
            try {
            is.close();
            } catch (IOException e) { /* ignore */ }
         }
    }
</script>

Upvotes: 4

Related Questions