Resolve the given jar file URL into a Jar File object. - Java Reflection

Java examples for Reflection:Jar

Description

Resolve the given jar file URL into a Jar File object.

Demo Code


//package com.java2s;

import java.io.IOException;

import java.net.URI;
import java.net.URISyntaxException;

import java.util.jar.JarFile;

public class Main {
    public static void main(String[] argv) throws Exception {
        String jarFileUrl = "java2s.com";
        System.out.println(getJarFile(jarFileUrl));
    }/*from www. j  ava  2  s  . c om*/

    /** URL prefix for loading from the file system: "file:" */
    public static final String FILE_URL_PREFIX = "file:";

    /**
     * Resolve the given jar file URL into a JarFile object.
     */
    protected static JarFile getJarFile(String jarFileUrl)
            throws IOException {
        if (jarFileUrl.startsWith(FILE_URL_PREFIX)) {
            try {
                return new JarFile(
                        new URI(jarFileUrl.replaceAll(" ", "%20"))
                                .getSchemeSpecificPart());
            } catch (URISyntaxException ex) {
                // Fallback for URLs that are not valid URIs (should hardly ever happen).
                return new JarFile(jarFileUrl.substring(FILE_URL_PREFIX
                        .length()));
            }
        } else {
            return new JarFile(jarFileUrl);
        }
    }
}

Related Tutorials