This question already has answers here:
How to write values in a properties file through java code
(4个答案)
5个月前关闭。
我无法写入我的属性文件,无法确定为什么不遇到任何类型的错误或其他原因。我已尝试调试,但未找到任何内容。这是我的
这就是我试图写入类中的属性文件的方式。
RequestId和ID
我的.properties文件中已经存在密钥。
How to write values in a properties file through java code不是我对该问题的答案,因为该文件中的答案会从属性文件中删除所有数据并保存您通过的内容。如我的问题在哪里验证特定于特定密钥。
经过测试并成功运行正常。
(4个答案)
5个月前关闭。
我无法写入我的属性文件,无法确定为什么不遇到任何类型的错误或其他原因。我已尝试调试,但未找到任何内容。这是我的
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
我的.properties文件中已经存在密钥。
How to write values in a properties file through java code不是我对该问题的答案,因为该文件中的答案会从属性文件中删除所有数据并保存您通过的内容。如我的问题在哪里验证特定于特定密钥。
最佳答案
这就是我们可以写入属性文件的方式。同样在下面的代码中,用于读取属性文件。
@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();
}
}
经过测试并成功运行正常。