java 如何从配置文件(.properties)中读取内容

1.如何创建.properties文件

很简单,建立一个txt文件,并把后缀改成.properties即可

2.将.properties文件拷入src的根目录下

3..properties文件内容格式

#注释

key=value

key2=value1

4.操作代码

 1     /*
 2      * 从配置文件中读取字段
 3      */
 4     public String GetValueByProperties(String KeyStr) {
 5         String result = "";
 6         try {
 7             InputStream in = this.getClass().getResourceAsStream("/config.properties");
 8             BufferedReader bf = new BufferedReader(new InputStreamReader(in));//据说这一句使用来读取中文用的
 9             Properties p = new Properties();
10             p.load(bf);
11             result = p.get(KeyStr).toString().trim();
12         } catch (Exception ex) {
13         }
14         return result;
15     }

说明:关于.properties读取中文问题

一定要注意一点,.properties文件的编码格式一定项目一致。

欢迎指正:haizi2014@qq.com
原文地址:https://www.cnblogs.com/hcfan/p/4585988.html