Question

I have a java-project that is developed with help of maven. Part of the project is unit-testing. I plan to put all temporary files that are produced by unittests into maven's target directory. This might be a good idea, because if for whatever reason temporary files are not removed by unittests, target directory may be cleaned and with it all temporary files still lying around in the file-system. So i found filtering function of the maven resources plugin and was wondering if it possible to instantiate it for my usecase. My plan is to have an entry in the properties file like this

targetdir = ${project.build.directory}

which should offer me a property that reveals the location of mavens target-directory. Now, caveeat is, the filtered property file is stored in the target directory by the maven resource plugin.
How can i find it there? I need the properties file to tell me where the target-directory is, but the properties-file is in the target directory? Is my approach still worth beeing done? Or is it not possible this way?

Was it helpful?

Solution

I have got two ways:

1. Use a Java Magic
Here, I just ran a trick

@Test
public void testpath(){
    //gets me surefire report dir, lies just below /target
    File testDir = new File(TestTargetPath.class.getResource("/").getPath());
    //Get its parent! location of target
    System.out.println("target? " + testDir.getParent());

    //modify your properties object to set this as targetDir
}

this prints

 target? /home/naishe/workspace/in/naishe/homeapp/target

2. Read the config file as resource using relative path

There are two places to put a resource file such as configuration properties in Maven layout.

  1. /src/main/resources -- the files under this goes as a part of artifact. You can access them using getResource() from any class under /src/main/java

  2. /src/test/resources -- files under this, does not go as a part of artifact, but they are available from any class /src/test/java.

So, based on what your need is, you can keep your config.properties under one or both the places and read the config files using:

    Properties props = new Properties();
    InputStream stream = AppConfig.class.getResourceAsStream("/config.properties");
    props.load(stream);
    System.out.println(">> " + props.getProperty("targetDir"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top