Java配置文件读取

1
2
3
# config/test.properties
key1=2018
key2=2019
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// TestProperties.java
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;
import java.util.stream.Collectors;

public final class TestProperties {
private static final Properties prop = new Properties();

static {
try {
prop.load(new java.io.FileInputStream(System.getProperty("user.dir").concat("/config/test.properties")));
} catch (IOException e) {
e.printStackTrace();
}
}

private TestProperties() {
}


public static void main(String args[]) {

// value
System.out.println(getValue("key1"));
System.out.println(getValue("key2"));

// array
System.out.println(Arrays
.stream(getValues(ImmutableList.of(
"key1",
"key2"
).toArray()))
.collect(Collectors.toList()));

// map
ImmutableMap<String, String> map = Maps.fromProperties(prop);
System.out.println(map);
}

public static String getValue(String key) {
return prop.getProperty(key).trim();
}

public static Object[] getValues(Object[] key) {
int length = key.length;
Object[] objects = new Object[length];
for (int i = 0; i < length; i++) {
objects[i] = prop.getProperty(key[i].toString()).trim();
}
return objects;
}
}