Java Jar File Find getJarFile(String classPath)

Here you can find the source of getJarFile(String classPath)

Description

Returns the full path of the jar file that contains the running class

License

Open Source License

Declaration


public static String getJarFile(String classPath) 

Method Source Code


//package com.java2s;
//===   it under the terms of the GNU General Public License as published by

import java.io.*;

import java.net.URLDecoder;

public class Main {
    /** Returns the full path of the jar file that contains the running class
      */// www  .j  ava 2s .c om

    public static String getJarFile(String classPath) {
        String dir = ClassLoader.getSystemResource(classPath).toString();

        try {
            dir = URLDecoder.decode(dir, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            //--- this should not happen but ...

            e.printStackTrace();
        }

        dir = dir.replace('\\', '/');

        if (dir.startsWith("jar:"))
            dir = dir.substring(4);
        if (dir.startsWith("file:"))
            dir = dir.substring(5);

        //--- skip the ending string "/"+clazz

        dir = dir.substring(0, dir.length() - classPath.length() - 1);

        //--- we must skip the "xxx.jar!" string (if the case)

        if (dir.endsWith("!"))
            dir = dir.substring(0, dir.length() - 1);

        //--- hack for windows : dirs like '/C:/...' must be changed to remove the
        //--- starting slash

        if (dir.startsWith("/") && dir.indexOf(':') != -1)
            dir = dir.substring(1);

        return dir;
    }
}

Related

  1. getJarFile(@Nonnull Class clazz)
  2. getJarFile(Class clazz)
  3. getJarFile(Class clazz)
  4. getJarFile(Class clazz)
  5. getJarFile(final ClassLoader loader)
  6. getJarFileByResourceName(Class clazz, String resourceName)
  7. getJarFolder(Class clazz)
  8. getJarLocation()
  9. getJarLocation(Class classFromJar)