How to get Maven project BaseDir() from java Code

You can't, because maven is used for building, and doesn't "exist" after the build.

If you need that during the build (for example via the exec plugin), then it is either accessible as a system propery or you can pass it as argument to the executed program.


According to maven doc, there's a maven property ${project.basedir}

If you include a properties file in your resources, which has the ${project.basedir} placeholder, and enable filtering for the resources plugin, you will find that there's a build time substitution of the basedir into the properties file. You can then load this using a Properties instance in code.

in /src/main/resources, create a file called project.properties, containing

my.basedir=${project.basedir}

Then, in the POM, enable filtering for /src/main/resources, as outlined in the maven resources filtering documentation linked above.

Then, in code, at runtime, load the properties file into a Properties instance

Properties props = new Properties();
props.load(this.getClass().getResourceAsStream("project.properties"));
String myBasedir = props.get("my.basedir");

An alternative would be to process some source files and do substitution in there by hooking into the process-sources phase, but that's not likely to be easy to explain.


I'm assuming that you want this when run from 'exec:exec' or 'test'. If that's the case, you can get it via

System.getProperties().get("basedir")

Tags:

Java

Maven 2