java-工具类-读取配置文件

/**
 * Company
 * Copyright (C) 2004-2018 All Rights Reserved.
 */
package com.yubin.test;

import java.io.*;
import java.net.URL;
import java.util.Properties;

/**
 * @author Administrator
 * @version $Id ProUtil.java, v 0.1 2018-01-25 22:11 Administrator Exp $$
 */
public class ProUtil {
    private static Properties props = null;
    private static File configFile = null;
    private static long fileLastModified = 0L;

    private static String configFileName = "spring/database.properties";

    private static void init() {
        URL url = ProUtil.class.getClassLoader().getResource(configFileName);


        configFile = new File(url.getFile());
        fileLastModified = configFile.lastModified();
        props = new Properties();
        load();
    }

    private static void load() {
        try {
            props.load(new InputStreamReader(new FileInputStream(configFile),"UTF-8"));
            fileLastModified = configFile.lastModified();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getConfig(String key) {
        if ((configFile == null) || (props == null)) init();
        if (configFile.lastModified() > fileLastModified) load(); //当检测到文件被修改时重新加载配置文件
        return props.getProperty(key);
    }

    public static void main(String[] args){
        System.out.println(getConfig("jdbc.driver"));
    }
}

  此文引用地址:

posted @ 2018-01-25 22:36  边境牧羊犬  阅读(367)  评论(0编辑  收藏  举报