Having spent a bunch of time writing functional tests for maven projects with many modules, I tend to end up needing access to the project base path (typically the path with the pom.xml file in it). This isn't much of a problem when running a single module - new File(".") pretty much does it. On the other hand when attempting to access modules outside of the jvm base path, things start to get tricky.
There's a couple ways to skin this cat - probably one of the more portable ones is a utility method that accepts a Class and a path and returns a File by checking the supplied Class' classloader:
There's a couple ways to skin this cat - probably one of the more portable ones is a utility method that accepts a Class and a path and returns a File by checking the supplied Class' classloader:
public static File getPathInModule(Class<?> classInModule,String ... items){ String tcPath = classInModule.getProtectionDomain().getCodeSource().getLocation().getFile(); String[] tcPathParts = StringUtils.split(tcPath,File.separator); StringBuffer pomPath = new StringBuffer(); for(String part:tcPathParts){ pomPath.append(File.separator); if("target".equals(part)){ break; } pomPath.append(part); } pomPath.append(StringUtils.join(items,File.separator)); return new File(pomPath.toString()); }This works fairly well as long as there is a target directory present, which is for my purposes - always. It could be modified to look for a pom.xml file instead though.