2013-07-25 99 views
2

由于我想利用一些Java库,我在Java中构建了一个Gradle插件。作为插件的一部分,我需要列出并处理文件的文件夹。我能找到的是如何做到这一点的gradle中生成文件的例子很多:如何使用Gradle的Java API定义过滤的FileTree?

FileTree tree = fileTree(dir: stagingDirName) 
    tree.include '**/*.md' 
    tree.each {File file -> 
    compileThis(file) 
    } 

但如何将使用摇篮的Java API做这在Java中?

底层的FileTree Java类具有非常灵活的输入参数,这使得它非常强大,但它很难弄清楚什么样的输入将实际工作。

回答

0

这是我这究竟是怎么在我的基于Java的任务的gradle:

public class MyPluginTask extends DefaultTask { 

    @TaskAction 
    public void action() throws Exception { 

     // sourceDir can be a string or a File 
     File sourceDir = new File(getProject().getProjectDir(), "src/main/html"); 
     // or: 
     //String sourceDir = "src/main/html"; 

     ConfigurableFileTree cft = getProject().fileTree(sourceDir); 
     cft.include("**/*.html"); 

     // Make sure we have some input. If not, throw an exception. 
     if (cft.isEmpty()) { 
      // Nothing to process. Input settings are probably bad. Warn user. 
      throw new Exception("Error: No processable files found in sourceDir: " + 
        sourceDir.getPath()); 
     } 

     Iterator<File> it = cft.iterator(); 
     while (it.hasNext()){ 
      File f = it.next(); 
      System.out.println("File: "+f.getPath()" 
     } 
    } 

} 
0

它实际上是相同的,例如, project.fileTree(someMap)。甚至有一个fileTree方法的超载,只需要基本目录(而不是地图)。代替each您可以使用for-each循环,而不是通常使用实现Action接口的匿名内部类的闭包(尽管fileTree似乎缺少这些方法重载)。 Gradle Build Language Reference有详细信息。 PS:您还可以利用Groovy的Java库。

相关问题