插件jar中的Gradle插件复制文件

时间:2011-12-29 18:31:00

标签: plugins resources jar task gradle

我正在创建我的第一个gradle插件。我正在尝试将文件从分发jar复制到我在项目中创建的目录中。虽然文件存在于jar中,但我无法将其复制到目录中。

这是我的任务代码:

import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;

class InitTask extends DefaultTask {

  File baseDir;

  private void copyEnvironment(File environments) {
    String resource =     getClass().getResource("/environments/development.properties").getFile();
    File input = new File(resource);
    File output = new File(environments, "development.properties");

    try {
      copyFile(input, output);
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }

  void copyFile(File sourceFile, File destFile) {
    destFile << sourceFile.text
  }

  @TaskAction
  void createDirectories() {
    logger.info "Creating directory."

    File environments = new File(baseDir, "environments");
    File scripts = new File(baseDir, "scripts");
    File drivers = new File(baseDir, "drivers");

    [environments, scripts, drivers].each {
      it.mkdirs();
    }

    copyEnvironment(environments);

    logger.info "Directory created at '${baseDir.absolutePath}'."
  }
}

这就是我得到的错误:

:init
java.io.FileNotFoundException:     file:/path-to-jar/MyJar.jar!/environments/development.properties (No such     file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:120)
    at groovy.util.CharsetToolkit.<init>(CharsetToolkit.java:69)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.newReader(DefaultGroovyMethods.java:15706)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.getText(DefaultGroovyMethods.java:14754)
    at org.codehaus.groovy.runtime.dgm$352.doMethodInvoke(Unknown Source)
    at org.codehaus.groovy.reflection.GeneratedMetaMethod$Proxy.doMethodInvoke(GeneratedMetaMethod.java:70)
    at groovy.lang.MetaClassImpl$GetBeanMethodMetaProperty.getProperty(MetaClassImpl.java:3465)
    at org.codehaus.groovy.runtime.callsite.GetEffectivePojoPropertySite.getProperty(GetEffectivePojoPropertySite.java:61)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:227)
    at br.com.smartcoders.migration.tasks.InitTask.copyFile(InitTask.groovy:29)

需要强调的是,development.properties位于MyJar.jar内的环境目录中

1 个答案:

答案 0 :(得分:1)

getClass().getResource()会返回一个网址。要访问该URL,您必须直接读取它(例如使用url.text),而不是先将其转换为字符串/文件。或者您可以使用getClass().getResourceAsStream().text,这可能更准确。在这两种情况下,您都可以选择指定文件编码。