Java Jar File Find findContainingJar(ClassLoader classLoader, String resourceName)

Here you can find the source of findContainingJar(ClassLoader classLoader, String resourceName)

Description

find Containing Jar

License

Apache License

Declaration

static public File findContainingJar(ClassLoader classLoader, String resourceName) 

Method Source Code


//package com.java2s;
/*/*  www. j  a  v  a 2 s  .  co m*/
 * Copyright 2015 Fizzed, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;

import java.net.MalformedURLException;

import java.net.URISyntaxException;
import java.net.URL;

public class Main {
    static public File findContainingJar(ClassLoader classLoader, String resourceName) {
        File jarFile;
        URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName);

        if ("jar".equals(url.getProtocol())) { //NOI18N

            String path = url.getPath();
            int index = path.indexOf("!/"); //NOI18N

            if (index >= 0) {
                try {
                    String jarPath = path.substring(0, index);
                    if (jarPath.contains("file://") && !jarPath.contains("file:////")) { //NOI18N
                        /* Replace because JDK application classloader wrongly recognizes UNC paths. */
                        jarPath = jarPath.replaceFirst("file://", "file:////"); //NOI18N
                    }
                    url = new URL(jarPath);

                } catch (MalformedURLException mue) {
                    throw new RuntimeException(mue);
                }
            }
        }
        try {
            jarFile = new File(url.toURI());
        } catch (URISyntaxException ex) {
            throw new RuntimeException(ex);
        }
        assert jarFile.exists();
        return jarFile;
    }
}

Related

  1. findContainingJar( @SuppressWarnings("rawtypes") Class my_class, ClassLoader loader)
  2. findContainingJar(Class my_class)
  3. findContainingJar(Class clazz)
  4. findContainingJar(Class clazz)
  5. findContainingJar(Class myClass, Map packagedClasses)
  6. findJar(Class klass)
  7. findJar(Class my_class)
  8. findJar(File dir)
  9. findJar(String nameRegexp)