Java tutorial
//package com.java2s; //License from project: Open Source License import java.io.File; import java.net.URLDecoder; import java.security.CodeSource; public class Main { /** * Returns the folder that contains a jar that contains the class * * @param aclass a class to find a jar * @return */ public static String getJarContainingFolderPath(Class aclass) throws Exception { CodeSource codeSource = aclass.getProtectionDomain().getCodeSource(); File jarFile; if (codeSource.getLocation() != null) { jarFile = new File(codeSource.getLocation().toURI()); } else { String path = aclass.getResource(aclass.getSimpleName() + ".class").getPath(); int startIndex = path.indexOf(":") + 1; int endIndex = path.indexOf("!"); if (startIndex == -1 || endIndex == -1) { throw new IllegalStateException( "Class " + aclass.getSimpleName() + " is located not within a jar: " + path); } String jarFilePath = path.substring(startIndex, endIndex); jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8"); jarFile = new File(jarFilePath); } return jarFile.getParentFile().getAbsolutePath(); } }