【问题标题】:append a json string to a file将 json 字符串附加到文件中
【发布时间】:2013-07-06 01:23:14
【问题描述】:

如何将 json 字符串附加到已经包含 json 字符串的文件(在 java 中)? 我尝试使用 objectmapper 将文件读入内存,然后将其附加并放回文件中。

ObjectMapper mapper = new ObjectMapper();
HashMap<String, Object> jsonMap = mapper.readValue( new File(workflowSessionFilePath), new TypeReference<HashMap<String, Object>>() {});

jsonMap.put("key", "value");
mapper.defaultPrettyPrintingWriter().writeValue(new File(workflowSessionFilePath), jsonMap);

但是还有比这更好的方法吗?

【问题讨论】:

  • 如何解析修改文件内容?请提供代码示例。

标签: java json


【解决方案1】:

java.nio.Files 中的方法:

public static Path write(Path path,
                         Iterable<? extends CharSequence> lines,
                         Charset cs,
                         OpenOption... options)

public static BufferedWriter newBufferedWriter(Path path,
                                               Charset cs,
                                               OpenOption... options)

如果选项不包括 CREATE,则打开现有文件,但永远不会创建新文件。
如果选项不包括 TRUNCATE,则保留现有内容并附加新内容。

来电:

java.nio.Files.write(new Path(...),
                     myOutputString,  // or StringBuffer/StringBuilder/Charbuffer
                     myCharset,       // e.g. java.nio.charset.Charset.forName("UTF8")
                     java.nio.file.StandardOpenOption.WRITE);


BufferedWriter bw =  java.nio.files.Files.newBufferedWriter(
                                               new Path(...),
                                               myCharset,
                                               java.nio.file.StandardOpenOption.WRITE);
for (...) {
      bw.write(...);
}
bw.flush();
bw.close();

【讨论】:

    猜你喜欢
    • 2014-11-18
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    相关资源
    最近更新 更多