Gradle file with plugin for copying from plugin

I am creating my first gradle plugin. I am trying to copy a file from the distribution to the directory that I created in the project. Although the file exists inside the jar, I cannot copy it to a directory.

This is my task code:

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}'." } } 

And this is the error I get:

 :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) 

To emphasize, development.properties is located inside the environment directory inside MyJar.jar

+6
source share
1 answer

getClass().getResource() returns the URL. To access this URL, you will need to read it directly (for example, using url.text ), and not first convert it to String / File. Or you can use getClass().getResourceAsStream().text , which is probably more accurate. In both cases, you can specify the encoding of the file.

+1
source

Source: https://habr.com/ru/post/904693/


All Articles