cy
2022-06-21 129904537f66509f97b285e7eb4f42b3dc349dd0
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package cn.ksource.core.util;
 
import cn.ksource.web.Constants;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
 
/**
 * 读取配置文件
 */
public class PropertyUtil {
 
    private static String fileName = Constants.APP_CONF_FILE;
    
    /**
     * 返回jdbc.properties的指定值
     * @param key
     * @return
     * 作者:杨凯
     */
    public static String get(String key){
        return get(fileName, key);
    }
    
    /**
     * 加载指定的配置文件,返回key所代表的value值
     * @param fileName property文件的名字(该文件最好放在根目录下)
     * @param key 键值
     * @return
     * 作者:杨凯
     */
    public static String get(String fileName,String key){
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        String value = "";
        try {
            InputStream in = classLoader.getResource(fileName).openStream();
            Properties props = new Properties();
            props.load(in);
            value = props.getProperty(key);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("读取配置文件失败");
        }
        return value;
    }
    
    public static void write(String fileName, String key, String value) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        String filePath =  classLoader.getResource(fileName).getPath();
        Properties prop = new Properties();
        try {
            InputStream fis = new FileInputStream(filePath);
            // 从输入流中读取属性列表(键和元素对)
            prop.load(fis);
            // 调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。
            // 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
            OutputStream fos = new FileOutputStream(filePath);
            prop.setProperty(key, value);
            // 以适合使用 load 方法加载到 Properties 表中的格式,
            // 将此 Properties 表中的属性列表(键和元素对)写入输出流
            prop.store(fos, "");
            fis.close();
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Visit " + fileName + " for updating " + key + " value error");
 
        }
    }
 
}