通过XXX.class.getResource 获取配置文件内容

2018-04-25  本文已影响0人  ffewi

文件目录结构:

源码展示:

/**
 * 通过XXX.class.getResource 获取配置文件
 *
 */
public class GetResource {

    public static void main(String[] args) throws Exception {
        GetResourceByJar byJar = new GetResourceByJar();
        // 默认路径
        URL defaultUrl = byJar.getClass().getResource("");
        // 绝对路径
        URL absoluteUrl = byJar.getClass().getResource("/");
        // 相对路径
        URL relationUrl = byJar.getClass().getResource("./tmp");

        Properties defaultProp = new Properties();

        defaultProp.load(new FileInputStream(defaultUrl.getPath() + "/"
                + "res.conf"));
        PrintProp(defaultProp);

        System.out.println("================================================");
        Properties absoluteProp = new Properties();
        absoluteProp.load(new FileInputStream(new File(absoluteUrl.getPath(),
                "src.conf")));
        PrintProp(absoluteProp);
        System.out.println("================================================");
        Properties relationProp = new Properties();
        relationProp.load(new FileInputStream(new File(relationUrl.getPath(),
                "tmp.conf")));

        PrintProp(relationProp);

    }

    /**
     * 配置文件内容 toString 打印
     * 
     * @param prop
     */
    public static void PrintProp(Properties prop) {
        Enumeration<Object> keys = prop.keys();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            System.out.println(key + ":" + prop.getProperty(key));
        }

    }

}

res.conf文件内容:

path = src/res/tmp.conf
description = current package path

src.conf文件内容:

path = src/tmp.conf
description = classpath path

tmp.conf文件内容:

path = src/res/tmp/tmp.conf
description = sub package path

测试输出结果:

description:current package path
path:src/res/tmp.conf
================================================
description:classpath path
path:src/tmp.conf
================================================
description:sub package path
path:src/res/tmp/tmp.conf

测试运行环境:

Eclipse Luna,JDK1.7

上一篇下一篇

猜你喜欢

热点阅读