JAVA 格式化JSON數(shù)據(jù)并保存到j(luò)son文件中的實(shí)例
使用fastjson格式化json數(shù)據(jù)并保存到文件
/** * 將JSON數(shù)據(jù)格式化并保存到文件中 * @param jsonData 需要輸出的json數(shù) * @param filePath 輸出的文件地址 * @return */ public static boolean createJsonFile(Object jsonData, String filePath) { String content = JSON.toJSONString(jsonData, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat); // 標(biāo)記文件生成是否成功 boolean flag = true; // 生成json格式文件 try { // 保證創(chuàng)建一個(gè)新文件 File file = new File(filePath); if (!file.getParentFile().exists()) { // 如果父目錄不存在,創(chuàng)建父目錄 file.getParentFile().mkdirs(); } if (file.exists()) { // 如果已存在,刪除舊文件 file.delete(); } file.createNewFile(); // 將格式化后的字符串寫入文件 Writer write = new OutputStreamWriter(new FileOutputStream(file), 'UTF-8'); write.write(content); write.flush(); write.close(); } catch (Exception e) { flag = false; e.printStackTrace(); } return flag; }
補(bǔ)充知識(shí):將json格式的數(shù)據(jù)保存到本地
1.創(chuàng)建jsonobject對(duì)象
JSONObject jsonObject = new JSONObject();
2.以鍵值的形式存儲(chǔ)數(shù)據(jù)
jsonObject.put(key, value);
3.將json格式的數(shù)據(jù)轉(zhuǎn)化成字符串
jsonObject.toString
4.往本地寫數(shù)據(jù)
//文件路徑String path = Environment.getExternalStorageDirectory().toString() + '/test.txt';//判斷文件是否存在File file = new File(path); if (file.exists()) { Log.i('myTag', '文件存在'); } else { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } Log.i('myTag', '文件創(chuàng)建成功'); } try { FileOutputStream fileOutputStream = new FileOutputStream(file); fileOutputStream.write(jsonString.getBytes()); // fileOutputStream.write(sbString.getBytes()); fileOutputStream.close(); Log.i('myTag', 'json數(shù)據(jù)保存到成功!!!'); } catch (Exception e) { e.printStackTrace(); }
以上這篇JAVA 格式化JSON數(shù)據(jù)并保存到j(luò)son文件中的實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算2. Spring如何集成ibatis項(xiàng)目并實(shí)現(xiàn)dao層基類封裝3. JS圖片懶加載庫(kù)VueLazyLoad詳解4. IDEA 2020.1.2 安裝教程附破解教程詳解5. Python 解決火狐瀏覽器不彈出下載框直接下載的問題6. Java利用TCP協(xié)議實(shí)現(xiàn)客戶端與服務(wù)器通信(附通信源碼)7. 使用AJAX(包含正則表達(dá)式)驗(yàn)證用戶登錄的步驟8. Java實(shí)現(xiàn)的迷宮游戲9. Java PreparedStatement用法詳解10. django queryset相加和篩選教程

網(wǎng)公網(wǎng)安備