Java ClassPath Get getClassPathRoot(Class cl)

Here you can find the source of getClassPathRoot(Class cl)

Description

get Class Path Root

License

Open Source License

Declaration

@SuppressWarnings("deprecation")
public static File getClassPathRoot(Class<?> cl) 

Method Source Code


//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);
    }
}

Related

  1. getClasspathResource(final String resource)
  2. getClasspathResource(String name)
  3. getClasspathResource(String path)
  4. getClasspathResourceAsFile(String resourceName)
  5. getClassPathResourcesAsStreams(String relativeResourceName)
  6. getClasspathString()