Here you can find the source of getClassPathRoot(Class> cl)
@SuppressWarnings("deprecation") public static File getClassPathRoot(Class<?> cl)
//package com.java2s; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; public class Main { @SuppressWarnings("deprecation") public static File getClassPathRoot(Class<?> cl) { try {/*from w ww. j a v a 2s. c o m*/ String resourceName = translateResourceName(cl); URL url = getClassURL(cl.getClassLoader(), resourceName); if (url.getProtocol().equals("file")) { String fileName = URLDecoder.decode(url.getPath()); String rootDirName = fileName.replaceAll(resourceName + "$", ""); return new File(rootDirName); } else { String jarFileName = url.getPath().replaceAll("\\!.*", ""); return new File(URLDecoder.decode(new URL(jarFileName).getPath())); } } catch (MalformedURLException e) { throw new RuntimeException(e); } } public static String translateResourceName(Class<?> cl) { String className = cl.getName(); String resourceName = className.replaceAll("\\.", "/") + ".class"; return resourceName; } public static URL getClassURL(Class<?> cl) { return getClassURL(cl.getClassLoader(), translateResourceName(cl)); } static URL getClassURL(ClassLoader cl, String resourceName) { return cl.getResource(resourceName); } }