Java URL Resolve resolveResourceAsURL(Class clazz, String name)

Here you can find the source of resolveResourceAsURL(Class clazz, String name)

Description

Same as java.lang.Class#getResource() but works with and without jars reliably.

License

Open Source License

Parameter

Parameter Description
clazz Base for the <code>getResource()</code> operation.
name name of the resource.

Exception

Parameter Description
IOException an exception

Return

URL to the resource or null if none found.

Declaration

public static URL resolveResourceAsURL(Class clazz, String name) 

Method Source Code

//package com.java2s;
/****************************************************************************
 * Copyright (C) 2012 ecsec GmbH.//from   w w  w .  j  av a2 s. co  m
 * All rights reserved.
 * Contact: ecsec GmbH (info@ecsec.de)
 *
 * This file is part of the Open eCard App.
 *
 * GNU General Public License Usage
 * This file may be used under the terms of the GNU General Public
 * License version 3.0 as published by the Free Software Foundation
 * and appearing in the file LICENSE.GPL included in the packaging of
 * this file. Please review the following information to ensure the
 * GNU General Public License version 3.0 requirements will be met:
 * http://www.gnu.org/copyleft/gpl.html.
 *
 * Other Usage
 * Alternatively, this file may be used in accordance with the terms
 * and conditions contained in a signed written agreement between
 * you and ecsec GmbH.
 *
 ***************************************************************************/

import java.net.URL;

public class Main {
    /**
     * Same as {@link java.lang.Class#getResource()} but works with and without jars reliably.
     * In fact the resource is tried to be loaded with and without / in front of the path.
     *
     * @param clazz Base for the <code>getResource()</code> operation.
     * @param name name of the resource.
     * @return URL to the resource or null if none found.
     * @throws IOException
     */
    public static URL resolveResourceAsURL(Class clazz, String name) {
        URL url = clazz.getResource(name);
        if (url == null) {
            name = name.startsWith("/") ? name.substring(1) : "/" + name;
            url = clazz.getResource(name);
        }
        return url;
    }
}

Related

  1. resolveHref(String baseUrl, String href)
  2. resolveManifestResources(final URL manifestUrl, final List resources)
  3. resolvePlatformUrl(String urlspec)
  4. resolveRelativeURL(final URL primaryUrl, final String relativeLoc)
  5. resolveRelativeURL(String contextUri, String relativeUri)
  6. resolveResourceURL(Class base, String resource)
  7. resolveRootUrl(Class knownClass)
  8. resolveUrl(String url, Properties properties)
  9. resolveURL(String urlValue)