最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I use Java in an Ant buildfile? - Stack Overflow

programmeradmin2浏览0评论

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>

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>
Share Improve this question edited Feb 12, 2011 at 0:26 martin clayton 78.3k33 gold badges218 silver badges200 bronze badges asked Dec 21, 2010 at 18:26 marc eshermarc esher 4,9213 gold badges38 silver badges54 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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>

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>
发布评论

评论列表(0)

  1. 暂无评论