Java中读取.properties配置文件的通用类

时间:2022-07-16 11:59:11

  由于Java中读取配置文件的代码比较固定,所以可以将读取配置文件的那部分功能单独作为一个类,以后可以复用。为了能够达到复用的目的,不能由配置文件中每一个属性生成一个函数去读取,我们需要一种通用的方法读取属性,即由用户给出属性名字(作为方法参数)来获取对应属性的Value值。下面是示例代码:

 1 import java.io.*;
2 import java.util.*;
3
4 import org.apache.commons.logging.Log;
5 import org.apache.commons.logging.LogFactory;
6
7
8 public class Configure {
9
10 // private static final Log log = LogFactory.getLog(ServerConfig.class);
11 private static Properties config = null;
12
13 public Configure() {
14 config = new Properties();
15 }
16
17 public Configure(String filePath) {
18 config = new Properties();
19 try {
20 ClassLoader CL = this.getClass().getClassLoader();
21 InputStream in;
22 if (CL != null) {
23 in = CL.getResourceAsStream(filePath);
24 }else {
25 in = ClassLoader.getSystemResourceAsStream(filePath);
26 }
27 config.load(in);
28 // in.close();
29 } catch (FileNotFoundException e) {
30 // log.error("服务器配置文件没有找到");
31 System.out.println("服务器配置文件没有找到");
32 } catch (Exception e) {
33 // log.error("服务器配置信息读取错误");
34 System.out.println("服务器配置信息读取错误");
35 }
36 }
37
38 public String getValue(String key) {
39 if (config.containsKey(key)) {
40 String value = config.getProperty(key);
41 return value;
42 }else {
43 return "";
44 }
45 }
46
47 public int getValueInt(String key) {
48 String value = getValue(key);
49 int valueInt = 0;
50 try {
51 valueInt = Integer.parseInt(value);
52 } catch (NumberFormatException e) {
53 e.printStackTrace();
54 return valueInt;
55 }
56 return valueInt;
57 }
58 }

单元测试:

    @Test
public void configureTest() {
Configure config
= new Configure("server.properties");
int port = config.getValueInt("server.port");
String ip
= config.getValue("server.ip");
String sp
= config.getValue("message.split");
System.out.println(
"port: " + port);
System.out.println(
"ip: " + ip);
System.out.println(
"sp: " + sp);
}

配置文件如下:

server.port =30000
server.ip
=127.0.0.1
server.backgroundRun
= false
MAX_ERROR_NUM
=1000
message.split
=\#
message.over
=31
message.serverGetMessage
=Yes
message.wrong
=No
message.serverGetOver
=over
message.serverFindSIM
=find
message.serverNotFindSIM
=NotFind