用ClassLoader读取资源文件

关于读取资源文件(如文本文件、图像、二进制文件等),一般不推荐直接给出操作系统的路径,而是给出相对于当前类的相对路径,这样就可以使用类的装载器来装载资源文件。常用的方法有:
Class类的getResourceAsStream(String resourcePath);
ClassLoader类的getResourceAsStream(String resourcePath)
Class类的该方法最终还是委派给ClassLoader的getResourceAsStream方法,但是使用中发现Class#getResourceAsStream()使用的是绝对路径(以/开头),而ClassLoader#getResourceAsStream()使用的相对路径。
propterty文件经常放在类路径的根路径下(最顶层包的上层目录,如classes),这样加载property文件时就可以先用Class#getResourceAsStream方法获取输入源,再从该输入源load各entry。
code piece:
package sinpo.usagedemo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import junit.framework.TestCase;

/**
 @author 徐辛波(sinpo.xu@hotmail.com)
 * Oct 19, 2008
 */
public class LoadResource extends TestCase {
    public void test() throws Exception {
        //usage 1: use absolute path (mostly used)
        InputStream in1 = this.getClass().getResourceAsStream("/sinpo/test2.properties");
        //usage 2: use relative path
        InputStream in2 = this.getClass().getClassLoader().getResourceAsStream("sinpo/test2.properties");
        //usage 3: use system class path
        InputStream in3 = ClassLoader.getSystemResourceAsStream("system.properties");
        
        //将读取的资源作为Properties的输入源
        Properties props = new Properties();
        props.load(in1);
        String propValue = props.getProperty("propKey");
        System.out.println(propValue);
        
        //将读取的资源作为文本输出
        InputStreamReader reader = new InputStreamReader(in1);
        BufferedReader bReader = new BufferedReader(reader);
        String content = bReader.readLine();
        //输出第一行内容
        System.out.println(content);
        
        //TODO close them
    }
}

posted on 2008-10-19 20:36 徐辛波 阅读(1253) 评论(0)  编辑  收藏 所属分类: source pieces


只有注册用户登录后才能发表评论。


网站导航:
 

导航

<2008年10月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

统计

常用链接

留言簿(1)

随笔分类

随笔档案

最新随笔

最新评论

阅读排行榜

评论排行榜