Locating jars using a class or Package

For my build process, I need to reference files stored inside of jars. This is normally done so:

jar:file:/path_to_jar.jar!/package1/package2/file.extension

The computation of this path can be done automatically in java.

public String getPath(Class clazz) {
	CodeSource containingJarFile = clazz.getProtectionDomain()
		.getCodeSource();

	String libLocation = "";
	if (containingJarFile != null) {

		libLocation = containingJarFile.getLocation().toString();

		if (libLocation.endsWith(".jar")) {
			libLocation = "jar:" + libLocation + "!/";
		}
	}

	return libLocation;
}

Just attach the path to the return of this method, and you can reference files inside jars.

The implementation is from the AcceleoCompiler Class from the Accleo Eclipse Project.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s