Java加载资源文件的两种方法
作者:网络转载 发布时间:[ 2013/4/19 10:27:23 ] 推荐标签:
在davenkin包下定义ResourceLoader.java来加载资源文件:
package davenkin;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ResourceLoader
{
public static void main(String[] args) throws IOException
{
ResourceLoader resourceLoader = new ResourceLoader();
resourceLoader.loadProperties1();
}
public void loadProperties1() throws IOException
{
InputStream input = null;
try
{
input = Class.forName("davenkin.ResourceLoader").getResourceAsStream("/resources/config.properties");
//also can be this way:
//input = this.getClass().getResourceAsStream("/resources/config.properties");
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
printProperties(input);
}
private void printProperties(InputStream input) throws IOException
{
Properties properties = new Properties();
properties.load(input);
System.out.println(properties.getProperty("name"));
}
}
输出结果为第二个resources文件夹下config.properties的内容:
ConfigUnderSrc
原因在于(请注意ReourceLoader.java文件中的红色部分):我们给出的资源文件路径(/resources/config.properties)以"/"开头,即使用的是定位方式,所以找到的是直接在classpath下的resources文件夹。如果去掉资源文件文件路径前的"/",则采用的是相对定位方式,此时应该输出davenkin/resources/config.properties文件的内容。
(二)用ClassLoader类加载资源文件
ClassLoader类也提供和Class类相同的加载方法:
public InputStream getResourceAsStream(String pathToConfigFile);
用ClassLoader加载配置文件时,pathToConfigFile均不能以"/"开头,在查找时直接在classpath下进行查找。Class类在查找资源文件时,也是代理(delegate)给ClassLoader完成查找功能的,请参考Java官方文档。

sales@spasvo.com