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

文件目录结构:

  • src
    • res
      • tmp
        • tmp.conf
      • GetResource.java
      • res.conf
    • src.conf

源码展示:

/**
 * 通过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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容