码迷,mamicode.com
首页 > 编程语言 > 详细

java读取properties文件

时间:2015-08-30 14:06:06      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

创建PropUtil类

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropUtil {
    /**
     * 获取config文件
     * @param 
     * @return
     */
    private static Properties properties = null;

    public PropUtil(String path) {
        initialize(path);
    }

    private void initialize(String path) {
        InputStream is = getClass().getClassLoader().getResourceAsStream(path);
        if (is == null) {

            return;
        }
        properties = new Properties();
        try {
            properties.load(is);
        } catch (IOException e) {

        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (Exception e) {

            }
        }
    }

    /**
     * get specified key in config files
     * 
     * @param key
     *            the key name to get value
     */
    public String get(String key) {
        String keyValue = null;
        if (properties.containsKey(key)) {
            keyValue = (String) properties.get(key);
        }
        return keyValue;
    }
}

创建Properties文件FrameWork.properties

name=linchaojiang
age=29
code=009045

创建测试类ReadFrameWorkProperties ,读取FrameWork.properties文件

public class ReadFrameWorkProperties {
    
    private static PropUtil PropUtil = new PropUtil(
            "config/FrameWork.properties");
    public static String name = PropUtil.get("name");


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(name);
        System.out.println(age);
        System.out.println(code);
    }

}

输出结果:

linchaojiang

29

009045

java读取properties文件

标签:

原文地址:http://www.cnblogs.com/lincj/p/4770704.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!