Java Jar File Find getJarOrDir(Class mainClass)

Here you can find the source of getJarOrDir(Class mainClass)

Description

Get JAR file or directory from where the given class is loaded.

License

Open Source License

Parameter

Parameter Description
mainClass Class to be loaded.

Return

JAR file name or directory, directory ends with "/"

Declaration

public static String getJarOrDir(Class<?> mainClass) 

Method Source Code

//package com.java2s;
/*/*from   w ww .  j a  va2  s. c o m*/
Copyright (c) 2014 Wolfgang Imig
    
This file is part of the library "Java Add-in for Microsoft Office".
    
This file must be used according to the terms of   
      
  MIT License, http://opensource.org/licenses/MIT
    
 */

import java.io.UnsupportedEncodingException;

import java.net.URLDecoder;

public class Main {
    /**
     * Get JAR file or directory from where the given class is loaded.
     * 
     * @param mainClass
     *            Class to be loaded.
     * @return JAR file name or directory, directory ends with "/"
     */
    public static String getJarOrDir(Class<?> mainClass) {
        // Get the location of the class files.
        // This might be a jar file or a directory.
        String jar = mainClass.getProtectionDomain().getCodeSource().getLocation().getPath();
        try {
            jar = URLDecoder.decode(jar, "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }

        if (jar.startsWith("/")) {
            jar = jar.substring(1);
        }
        return jar;
    }
}

Related

  1. getJarLocation()
  2. getJarLocation(Class classFromJar)
  3. getJarLocation(Class clazz)
  4. getJarLocation(final Class cClass)
  5. getJarManifest(File file)
  6. getJarPath(Class caller)
  7. getJarPath(String pkg)
  8. getJarPathOf(Class classObject)