gpt4 book ai didi

java - 如何读取/写入用冒号 ':' 而不是等于 '=' 分隔键和值的属性文件

转载 作者:行者123 更新时间:2023-12-02 11:34:47 26 4
gpt4 key购买 nike

我有包含键:值列表的属性文件,如下所示:

key1 : value1
key2 : value2

如何使用 Properties 类读取和写入该文件?可能还是不可能?

最佳答案

我查看了java Properties类(在jdk中),发现java使用常量'='通过以下方法保存属性文件:

private void store0(BufferedWriter bw, String comments, boolean escUnicode)
throws IOException
{
if (comments != null) {
writeComments(bw, comments);
}
bw.write("#" + new Date().toString());
bw.newLine();
synchronized (this) {
for (Enumeration<?> e = keys(); e.hasMoreElements();) {
String key = (String)e.nextElement();
String val = (String)get(key);
key = saveConvert(key, true, escUnicode);
/* No need to escape embedded and trailing spaces for value, hence
* pass false to flag.
*/
val = saveConvert(val, false, escUnicode);
bw.write(key + "=" + val);
bw.newLine();
}
}
bw.flush();
}

所以,无法处理我的属性文件。但是对于删除/写入我的属性文件,我发现该文件是 yaml 格式,我们可以通过此方法轻松读取文件:

public Map read(String path) {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
try {
File file = new File(path);
Map map = mapper.readValue(file, Map.class);
return map;
} catch (Exception e) {
logger.error("Error during read Yml file {}", path, e);
}
return new HashMap();
}

并通过以下方法更新文件:

public boolean update(String path, Map content) {
try {
YAMLFactory yamlFactory = new YAMLFactory();
yamlFactory.enable(YAMLGenerator.Feature.MINIMIZE_QUOTES);

File file = new File(path);
ObjectMapper mapper = new ObjectMapper(yamlFactory);
ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
writer.writeValue(file, content);
return true;
} catch (Exception e) {
logger.error("Error during save Yml file {}", path, e);
}
return false;
}

重要的是,我使用以下代码来防止对值使用双引号:

yamlFactory.enable(YAMLGenerator.Feature.MINIMIZE_QUOTES);

关于java - 如何读取/写入用冒号 ':' 而不是等于 '=' 分隔键和值的属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49026338/

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