Vikram
Vikram

Reputation: 7517

Get the target directory path in Maven (Java)

In a Maven project I want write some test results into a file in target directory of the project. Whenever, I get the project directory, it is actually getting the IntelliJ project directory instead of actual Maven directory.

Upvotes: 11

Views: 26689

Answers (6)

Virtuos
Virtuos

Reputation: 1

You need to obtain the location of the class, where you are running your logic in order to get the location of the target path. I use the following code in order to achieve that:

URL target = this.getClass().getClassLoader().getResource("org/mycomp/home/model").toURI().toURL();

Upvotes: 0

The following solutions work for me:

URL location = YourClass.class.getProtectionDomain().getCodeSource().getLocation();
String path = location.getFile().replace("/test-classes/","").replace("/classes/","");

or

Path targetPath = Paths.get(getClass().getResource("/").toURI()).getParent();
String path = targetPath.toString();

Upvotes: 1

Jens Vagts
Jens Vagts

Reputation: 675

I'm using the classloaders root resource path for retrieving projects build directory with following single line:

Path targetPath = Paths.get(getClass().getResource("/").toURI()).getParent();

The root resource path points to test-classes and it's parent is the desired path regardless of running the test via maven surefire or a JUnit runner of the IDE like Eclipse.

Upvotes: 3

twalthr
twalthr

Reputation: 2644

You could also use java.nio.file.Paths:

URL url = Paths.get("target", "results.csv").toUri().toURL();

Upvotes: 13

Mia Mano
Mia Mano

Reputation: 51

I used the answer above with a slight modification (I can't add comments). Since tests are placed into the 'test' folder, their classes will reside in 'target/test-classes' (so replacing 'classes' might not give you the expected result). Instead, I used the following:

File targetClassesDir = new File(ExportDataTest.class.getProtectionDomain().getCodeSource().getLocation().getPath());
File targetDir = targetClassesDir.getParentFile();

Upvotes: 5

Vikram
Vikram

Reputation: 7517

I got the solution for this. Here is how I am implementing. I have my own class CSVReader which uses CSVReader library. I am writing my results in results.csv file under target directory.

URL location = CSVReader.class.getProtectionDomain().getCodeSource().getLocation();
String path = location.getFile().replace("classes/","") + "results.csv";

In the above code I am getting the target directory path and removing the classes/ by string replace method and appending my desired file name. Hope this might help someone.

Upvotes: 6

Related Questions