2013-07-06 38 views
-3

如何將json字符串附加到已包含json字符串的文件(在java中)? 我嘗試使用objectmapper將文件讀入內存,然後將其追加並放回到文件中。將json字符串附加到文件中

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

你如何解析和修改文件的內容?請提供代碼示例。 – 2013-07-06 01:24:40

回答

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();