java保存properties时会自动转义

本文介绍如何使用Java操作Properties文件,并实现保存时不进行转义的方法。通过修改默认的保存方式,避免了属性值中特殊字符被转义的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用properties自带的保存方法,会自动进行转义: 如:url=http://www.baidu.com 保存后变为: url=http://www.baidu.com

Properties prop = new Properties();
File propertiesFile = new File(filePath);
try {
	InputStream fis = new FileInputStream(filePath);
	prop.load(fis);
	OutputStream fos = new FileOutputStream(filePath);
	prop.setProperty(parameterName, parameterValue);
	prop.store(fos, "Update '" + parameterName + "' value");
}catch (IOException e) {
	System.err.println("Visit " + filePath + " for updating " + parameterName + " value error");
}

将自带的store改为直接保存,不转义:

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));
bw.newLine();
for(Enumeration<?> e = prop.keys(); e.hasMoreElements();) {
	String key = (String)e.nextElement();
	String val = prop.getProperty(key);
	bw.write(key + "=" + val);
	bw.newLine();
}
bw.flush();

转载于:https://my.oschina.net/u/1468280/blog/888340