Here you can find the source of resolveResourceURL(Class> base, String resource)
Parameter | Description |
---|---|
base | - the base class for resolving classpath resources - may be null |
resource | - the resource to resolve |
Parameter | Description |
---|---|
IOException | - if something gnarly happens, or we can't find your resource |
public static URL resolveResourceURL(Class<?> base, String resource) throws IOException
//package com.java2s; /** /* ww w .j av a 2 s. c o m*/ * (C) Copyright 2009 Hal Hildebrand, All Rights Reserved * * 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.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Logger; public class Main { /** * Resolve a resource. First see if the supplied resource is an URL. If so, * open it and return the stream. If not, try for a file. If that exists and * is not a directory, then return that stream. Finally, look for a * classpath resource, relative to the supplied base class. If that exists, * open the stream and return that. Otherwise, barf * * @param base * - the base class for resolving classpath resources - may be * null * @param resource * - the resource to resolve * @return the URL of the resolved resource * @throws IOException * - if something gnarly happens, or we can't find your resource */ public static URL resolveResourceURL(Class<?> base, String resource) throws IOException { try { URL url = new URL(resource); return url; } catch (MalformedURLException e) { Logger.getAnonymousLogger().fine(String .format("The resource is not a valid URL: %s\n Trying to find a corresponding file", resource)); } File configFile = new File(resource); if (!configFile.exists()) { if (base == null) { throw new FileNotFoundException(String.format("resource does not exist as a file: %s", resource)); } } else if (configFile.isDirectory()) { Logger.getAnonymousLogger().fine( String.format("resource is a directory: %s\n Trying to find corresponding resource", resource)); } else { return configFile.toURI().toURL(); } return base.getResource(resource); } }