如何将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);
但是有比这更好的方法吗?
答案 0 :(得分:0)
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();