如何解决读取和写入Java属性而无需Unicode转义
这个问题可能已经被提出并回答了100次,但不幸的是我没有找到适合我的问题的任何东西。
以下情况:我有一个问题,当我读取属性以更改它们然后再次写入它们时,所有特殊字符都将转义为Unicode。
例如“:”变为“ \:”或 Descripción变为Descripci \ u00F3n
是否有一种方法可以更改存储方法,以便不转义特殊字符?
非常感谢
这是我编写属性的代码:
private static void writeUpdatedPropertiesFile(Properties newProperties,File sourceAndDestinationFile) {
sourceAndDestinationFile.delete();
try (FileOutputStream out = new FileOutputStream(sourceAndDestinationFile)) {
newProperties.store(out,null);
}
catch (final IOException e) {
e.printStackTrace();
}
}
解决方法
您可以使用store(Writer)代替store(OutputStream)。您可以使用任何所需的字符集构造一个OutputStreamWriter:
try (Writer out = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(sourceAndDestinationFile),StandardCharsets.UTF_8))) {
newProperties.store(out,null);
} catch (IOException e) {
e.printStackTrace();
}
当然,您有责任知道该文件是UTF-8文件,并使用load(Reader)而不是InputStream来读取它:
try (Reader in = new BufferedReader(
new InputStreamReader(
new FileInputStream(sourceAndDestinationFile),StandardCharsets.UTF_8))) {
properties.load(in);
} catch (IOException e) {
// ...
}
,
我通过自定义writer方法解决了该问题:
private static void writeProperties(Properties properties,File destinationFile) {
try (final BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(destinationFile),"Cp1252"))) {
for (final Object o : properties.entrySet()) {
final String keyValue = o.toString();
writer.write(keyValue + "\r\n");
}
}
catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。