gpt4 book ai didi

java - 无法在 java 中写入我的属性文件

转载 作者:太空宇宙 更新时间:2023-11-04 09:20:11 25 4
gpt4 key购买 nike

我无法写入我的属性文件,不确定为什么,因为没有遇到任何类型的错误或其他问题。我尝试过调试但没有发现任何结果。这是我的PropertiesUtil类。

public class PropertyUtil {

public static PropertyUtil prop;
private Properties properties;

public PropertyUtil() {
properties = new Properties();
}

public static synchronized PropertyUtil getInstance() {
if (prop == null) {
prop = new PropertyUtil();
}
return prop;
}

public void load(String fileName) throws IOException {
InputStream input = null;
input = getClass().getClassLoader().getResourceAsStream(fileName);
properties.load(input);
}

public void load(File file) throws IOException {
InputStream input = new FileInputStream(file);
properties.load(input);
}

public void clear() {
properties.clear();
}

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

public void setValue(String key, String value) {
properties.setProperty(key, value);
}

public HashMap<String, String> propertiesMap() {
HashMap<String, String> map = new HashMap<String, String>((Map) properties);
return map;
}

public void propertytonull() {
prop = null;
}
}

这就是我试图在类中写入属性文件的方式。

prop.setValue("RequestId",res_RequestId);
prop.setValue("Id",res_Id);

RequestId 和 Id

is key 已存在于我的 .properties 文件中。

How to write values in a properties file through java code不是我的问题的答案作为该文件中的答案,从属性文件中删除所有数据并保存您传递的内容。我的问题是针对特定 key 进行验证。

最佳答案

这就是我们写入属性文件的方式。下面还编写了用于从属性文件读取的代码。

@Test  
public void momSave() {
FileReader reader = null;
try {
reader = new FileReader(filepath/name.properties);
Properties p = new Properties();
p.load(reader);
p.getProperty("RequestId"); // to read from the property file
p.setProperty("RequestId","53403"); // to read into a property file
properties.store(filepath/name.properties),
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

经过测试并成功工作正常。

关于java - 无法在 java 中写入我的属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58407631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com