加载properties文件属性的Java工具类实现

来源:互联网 发布:linux基础知识学习 编辑:程序博客网 时间:2024/05/16 08:50

今天有点无聊,写了一个如何读取properties文件配置信息的类,其实这个功能在java.util包中已经有了相应的功能,但是我还是想要实现一下,以检测自己的编程能力
代码如下:

import java.io.BufferedReader;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.util.HashMap;public class Properties {    static HashMap<String, String> hashMap = new HashMap<String, String>();    @SuppressWarnings("resource")    public static void getProperties(String properties) throws IOException{        BufferedReader bufferedReader = null;        bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(properties)));        String str = null;        while ((str=bufferedReader.readLine()) != null) {            int index = str.indexOf("=");            if(index != -1){                hashMap.put(str.substring(0,index).trim(), str.substring(index+1).trim());            }        }    }    public static String getProperties(String key, String defalutvalue){        String value = hashMap.get(key);        if(value == null){            value = defalutvalue;        }        return value;    }    public static String getProperties(String propertiesFileName, String key, String defalutvalue) throws IOException{        getProperties(propertiesFileName);        return getProperties(key, defalutvalue);    }    public static void main(String[] args) throws IOException {        String valueString = getProperties("C:/Users/Kin.Liufu/Desktop/一点小心得/config.properties","userName","kin");        System.out.println(valueString);    }}
0 0
原创粉丝点击