1 package com.hager.util;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.util.Map;
8 import java.util.Properties;
9
10 /**
11 * @Author wzh
12 * @Date 2017/1/16.
13 * @Version V1.0 15 * @Description 读取properties配置帮助类
16 */
17 public class PropertiesUtil {
18
19
20 private PropertiesUtil() {
21 }
22
23 /**
24 * 读取properties文件
25 *
26 * @param file 文件路径
27 * @return 返回properties 对象
28 */
29 public static Properties fromFile(String file) {
30 InputStream stream = null;
31
32 try {
33 stream = new FileInputStream(new File(file));
34 return fromStream(stream);
35 } catch (IOException e) {
36 throw new RuntimeException(e);
37 } finally {
38 close(stream);
39 }
40 }
41
42 /**
43 * 读取properties文件
44 *
45 * @param file 文件路径
46 * @return 返回properties 对象
47 */
48 public static Properties fromClasspath(String file) {
49 InputStream stream = null;
50 try {
51 stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(file);
52 return fromStream(stream);
53 } catch (Exception e) {
54 throw new RuntimeException(e);
55 } finally {
56 close(stream);
57 }
58 }
59
60 /**
61 * convert stream to properties
62 *
63 * @param stream InputStream
64 * @return Properties
65 * @throws IOException
66 */
67 private static Properties fromStream(InputStream stream) throws IOException {
68 Properties dest = new Properties();
69 Properties src = new Properties();
70 src.load(stream);
71
72 // 如果key value为字符串,需要trim一下
73 for (Map.Entry<Object, Object> entry : src.entrySet()) {
74 Object key = entry.getKey();
75 Object value = entry.getValue();
76
77 Object newKey = key;
78 Object newValue = value;
79 if (newKey instanceof String) {
80 newKey = key.toString().trim();
81 }
82
83 if (newValue instanceof String) {
84 newValue = value.toString().trim();
85 }
86
87 dest.put(newKey, newValue);
88 }
89
90 return dest;
91 }
92
93 /**
94 * dispose stream
95 *
96 * @param stream InputStream
97 */
98 private static void close(InputStream stream) {
99 if (stream != null) {
100 try {
101 stream.close();
102 } catch (IOException e) {
103 }
104 }
105 }
106 }
配置文件:
位于
src/main/resources/test.properties;
内容简单:
test=aaa
测试:
1 @Test
2 public void fromClasspath() throws Exception {
3 String fileName = "test.properties";
4
5 Properties properties = PropertiesUtil.fromClasspath(fileName);
6 String values = properties.getProperty("test");
7 System.out.println(JsonHelper.serialize(properties));
8
9 Assert.assertEquals("aaa", values);
10 Assert.assertNotNull(properties);
11 }
结果:
{"test":"aaa"}
Process finished with exit code 0