直接上代码:
package org.commons;
import java.net.URL;
public class PropertiesUtil {
/**
*
* @param path
* 文件名
* @return 该文件的URL
*/
public static URL findAsResource(String path) {
URL url = null;
// First, try to locate this resource through the current
// context classloader.
ClassLoader contextClassLoader = Thread.currentThread()
.getContextClassLoader();
if (contextClassLoader != null) {
url = contextClassLoader.getResource(path);
}
if (url != null)
return url;
// Next, try to locate this resource through this class's classloader
url = PropertiesUtil.class.getClassLoader().getResource(path);
if (url != null)
return url;
// Next, try to locate this resource through the system classloader
url = ClassLoader.getSystemClassLoader().getResource(path);
// Anywhere else we should look?
return url;
}
}
本文介绍了一个名为PropertiesUtil的Java工具类,该类提供了一个静态方法findAsResource,用于通过不同的类加载器查找并返回指定路径下文件的URL。文章详细解释了如何首先尝试使用当前线程的上下文类加载器来定位资源,如果失败,则依次尝试使用调用该方法的类的类加载器以及系统类加载器。
2769

被折叠的 条评论
为什么被折叠?



