Move a text file into target folder when compiling a Maven project

mat_boy picture mat_boy · May 4, 2013 · Viewed 78.4k times · Source

I have a slight different version of the question that I made recently. I have a Maven project under Netbeans 7.3, which doesn't have any build.xml file to configure building options, while there is the pom.xml that I use to import other libraries. Now, I have a text file (let's say textfile.txt) stored in the project folder in Netbeans 7.3, e.g.

project folder
  textfile.txt
  src
    package
    package.subpackage
      MyClass.java

When I compile I get a target folder where the jar file is put in, e.g.

project folder
  textfile.txt
  target
    classes
    generated-sources
    ....etc
    test-classes
    MyProject.jar
  src
    package
    package.subpackage
      MyClass.java

How can I make the file textfile.txt being copied under target folder when I compile the Maven project?

Answer

JeanValjean picture JeanValjean · May 4, 2013

A first way is to put the files into src/main/resources that is the folder devoted to store the complied resources, i.e. the resources included into the jar file (e.g. images for the icons).

If you need to make the config file to be distributed with the jar, but separated by it, you must edit the pom.xml file. A possible answer is the to add the following plugin between the <plugins> and </plugins> tags.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.8</version>
    <executions>
        <execution>
            <phase>test</phase>
            <goals>
                <goal>run</goal>
            </goals>
            <configuration>
                <tasks>
                    <echo>Using env.test.properties</echo>
                    <copy file="textfile.txt" tofile="${basedir}/target/textfile.txt"/>
                    </tasks>
                </configuration>
            </execution>
        </executions>
    </plugin>

Moreover, as you can read here you can also import all the resources from an "input" directory to an "output" directory inside target by using the dedicated plugin, e.g.:

<plugin>
    <artifactId>maven-resources-plugin</artifactId>
    <version>3.0.1</version>
    <executions>
         <execution>
            <id>copy-resources</id>
            <!-- here the phase you need -->
            <phase>validate</phase>
            <goals>
               <goal>copy-resources</goal>
            </goals>
            <configuration>
               <outputDirectory>${basedir}/target/output</outputDirectory>
               <resources>          
                    <resource>
                        <directory>input</directory>
                        <filtering>true</filtering>
                    </resource>
               </resources>              
            </configuration>            
        </execution>
     </executions>
</plugin>