张世豪
8 天以前 de75ec84e295c3f952a200897aa22aa73d7d5867
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
package denglu;
import java.io.*;
import java.util.Properties;
 
public class UserChuShiHua {
    private static Properties userProperties;
    private static final String FILE_PATH = "user.properties";
 
    // 初始化方法:从文件加载数据到内存
    public static void initialize() {
        userProperties = new Properties();
        try (InputStream input = new FileInputStream(FILE_PATH)) {
            userProperties.load(input);
            System.out.println("用户数据初始化成功!");
        } catch (IOException e) {
            System.err.println("初始化失败,文件未找到或读取错误: " + e.getMessage());
        }
    }
 
    // 更新属性值并保存到文件
    public static void updateProperty(String key, String value) {
        if (userProperties == null) {
            System.err.println("错误:请先调用 initialize() 方法初始化数据!");
            return;
        }
        
        userProperties.setProperty(key, value);
        
        try (OutputStream output = new FileOutputStream(FILE_PATH)) {
            userProperties.store(output, "Updated User Properties");
        } catch (IOException e) {
            System.err.println("更新失败,文件写入错误: " + e.getMessage());
        }
    }
 
    // 获取属性值(可选辅助方法)
    public static String getProperty(String key) {
        if (userProperties == null) {
            initialize();
        }
        return userProperties.getProperty(key);
    }
 
 
}