关于properties文件的读取,应该满足多数情况的需要,但是碰到一个问题,就是原本可以正常读取的文件,打包成.jar就不能正确读取了。
想到“Commons
Logging就会使用Log4j和它在上下文类路径中找到的log4j.properties文件。”于是翻看commonsLogging的源码,发现在simpleLog.java的类里有这么读取properties文件的。
InputStream in =
getResourceAsStream("simplelog.properties");
这里他用了自己的getResourceAsStream()方法
/**
* Return the thread context class loader if available.
* Otherwise return null.
*
* The thread context class loader is available for JDK 1.2
* or later, if certain security conditions are met.
*
* @exception LogConfigurationException if a suitable class
loader
* cannot be identified.
*/
private
static ClassLoader getContextClassLoader()
{
ClassLoader classLoader = null;
if (classLoader == null) {
try {
// Are we running on a JDK 1.2 or later system?
Method method = Thread.class.getMethod("getContextClassLoader",
null);
// Get the thread context class loader (if there is one)
try {
classLoader = (ClassLoader)method.invoke(Thread.currentThread(),
null);
} catch (IllegalAccessException e) {
; // ignore
} catch (InvocationTargetException e) {
/**
* InvocationTargetException is thrown by 'invoke' when
* the method being invoked (getContextClassLoader) throws
* an exception.
*
* getContextClassLoader() throws SecurityException when
* the context class loader isn't an ancestor of the