Java ClassPath loadFromClasspath(Class clazz, String fileName)

Here you can find the source of loadFromClasspath(Class clazz, String fileName)

Description

load From Classpath

License

Open Source License

Declaration

@SuppressWarnings("rawtypes")
    public static URL loadFromClasspath(Class clazz, String fileName) 

Method Source Code

//package com.java2s;
/**// w ww  .j a v a2s . c  o  m
 * This software is released under the University of Illinois/Research and Academic Use License. See
 * the LICENSE file in the root folder for details. Copyright (c) 2016
 *
 * Developed by: The Cognitive Computations Group, University of Illinois at Urbana-Champaign
 * http://cogcomp.cs.illinois.edu/
 */

import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class Main {
    @SuppressWarnings("rawtypes")
    public static URL loadFromClasspath(Class clazz, String fileName) {
        URL dirURL = clazz.getResource("/" + fileName);
        if (dirURL == null)
            return null;

        URL url = null;
        try {
            String dirPath = dirURL.getPath();

            if (dirURL.getProtocol().equals("jar")) {
                int exclamation = dirPath.indexOf("!");
                String jarPath = dirPath.substring(5, exclamation);
                String jarRoot = dirPath.substring(0, exclamation + 1);

                JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
                Enumeration<JarEntry> entries = jar.entries();

                while (entries.hasMoreElements()) {
                    JarEntry element = entries.nextElement();
                    String name = element.getName();
                    if (name.equals(fileName)) {
                        url = new URL("jar:" + jarRoot + "/" + name);
                    }
                }
                jar.close();
            }
        } catch (Exception e) {
            System.err.println("ERROR: Can't read file : " + fileName + "\n" + e);
            e.printStackTrace();
            System.exit(1);
        }
        return url;
    }
}

Related

  1. getStreamFromClassPath(String source)
  2. getSystemClassPath()
  3. getSystemClasspathEntries()
  4. isInClassPath(String location)
  5. loadDirectoryFromClasspath(String path)
  6. loadFromClasspath(final String configFileName)
  7. loadResourceFromClasspath(Class clazz, String resourceName)
  8. parseClassPath(String classpath)
  9. parseJavaClassPath()