Code for getting the directory packaged code is running from


Details:

This code gets hold of the directory the current code is running from, stripping out any package structure.


Original author/s: ESRI
Original location/s: How to consume custom geoprocessing tools in Java applications
Adapted by: Andy Evans (generalised and fixed return variable)
License: unknown


Imports and instance variables:

	// None


Code:

	private String getCurrentSrcDir(){
		// Get classname, including package info.
		String fullyQualifiedClassName = this.getClass().getName();
		
		// Strip off .class
		String classFile = fullyQualifiedClassName.substring(fullyQualifiedClassName.lastIndexOf(".") + 1) + ".class";
		
		// Get the path to the running class.
		String pathIncludingClassFile = this.getClass().getResource(classFile).getPath();

		// Convert package elements to directories in name.
		fullyQualifiedClassName = fullyQualifiedClassName.replace(".", "/");
		
		// Strip the full name, including package directories, from path.
		String pathToSrcDir = null;
		String osName = System.getProperty("os.name");
		
		if (osName.toLowerCase().startsWith("win")){
			pathToSrcDir = pathIncludingClassFile.substring(1,pathIncludingClassFile.lastIndexOf(fullyQualifiedClassName) - 1);
		} else {
			pathToSrcDir = pathIncludingClassFile.substring(0,pathIncludingClassFile.indexOf(fullyQualifiedClassName) - 1);
		}
		
		return pathToSrcDir;
	}