6

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>
martin clayton
  • 76,436
  • 32
  • 213
  • 198
marc esher
  • 4,871
  • 3
  • 36
  • 51

2 Answers2

5

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>
martin clayton
  • 76,436
  • 32
  • 213
  • 198
marc esher
  • 4,871
  • 3
  • 36
  • 51
4

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>
David J. Liszewski
  • 10,959
  • 6
  • 44
  • 57
  • thanks a lot. I tried that initially but got the "Unable to create javax script engine for beanshell" error – marc esher Dec 21 '10 at 19:24
  • 1
    See this answer http://stackoverflow.com/questions/2716646/beanshell-in-ant-yielding-unable-to-create-javax-script-engine-for-beanshell/2718861#2718861 for adding required jars to build configuration to eliminate that error. – David J. Liszewski Dec 21 '10 at 19:46
  • Many thanks. If I can get that to work without adding it to ANT's classpath -- i.e. include that jar in my project and reference it in a classpathref -- then that's a winner. – marc esher Dec 21 '10 at 20:55