根据文件名获得properties文件

本文介绍了一个名为PropertiesUtil的Java工具类,该类提供了一个静态方法findAsResource,用于通过不同的类加载器查找并返回指定路径下文件的URL。文章详细解释了如何首先尝试使用当前线程的上下文类加载器来定位资源,如果失败,则依次尝试使用调用该方法的类的类加载器以及系统类加载器。
直接上代码:
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;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值