Java Class Path getApplicationPath(Class cls)

Here you can find the source of getApplicationPath(Class cls)

Description

get Application Path

License

Apache License

Declaration

public static String getApplicationPath(Class cls) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    public static String getApplicationPath(Class cls) {
        if (cls == null)
            throw new java.lang.IllegalArgumentException("parameter is not null !");
        ClassLoader loader = cls.getClassLoader();
        String clsName = cls.getName() + ".class";
        Package pack = cls.getPackage();
        System.out.println("package name is : " + (pack == null));
        String path = "";
        if (pack != null) {
            String packName = pack.getName();
            if (packName.startsWith("java.") || packName.startsWith("javax."))
                throw new java.lang.IllegalArgumentException("This is system class");
            clsName = clsName.substring(packName.length() + 1);
            if (packName.indexOf(".") < 0)
                path = packName + "/";
            else {
                int start = 0, end = 0;
                end = packName.indexOf(".");
                while (end != -1) {
                    path = path + packName.substring(start, end) + "/";
                    start = end + 1;//from ww w .j a  v a 2  s  .c o  m
                    end = packName.indexOf(".", start);
                }
                path = path + packName.substring(start) + "/";
            }
        }
        java.net.URL url = loader.getResource(path + clsName);
        String realPath = url.getPath();
        int pos = realPath.indexOf("file:");
        if (pos > -1)
            realPath = realPath.substring(pos + 5);
        pos = realPath.indexOf(path + clsName);
        realPath = realPath.substring(0, pos - 1);
        if (realPath.endsWith("!"))
            realPath = realPath.substring(0, realPath.lastIndexOf("/"));
        try {
            realPath = java.net.URLDecoder.decode(realPath, "utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return realPath;
    }
}

Related

  1. getAbsolutePath(Class theClass, String path)
  2. getAbsolutePath(final Class clazz, final String relative)
  3. getAppPath(Class clazz)
  4. getClass(String parentPath, String className)
  5. getClassAbsolutePath(Class c)
  6. getClassBasePath(Class aClass)