JAVA 格式化JSON數(shù)據(jù)并保存到j(luò)son文件中的實例
使用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)建一個新文件 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; }
補充知識:將json格式的數(shù)據(jù)保存到本地
1.創(chuàng)建jsonobject對象
JSONObject jsonObject = new JSONObject();
2.以鍵值的形式存儲數(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文件中的實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
javascript與jsp發(fā)送請求到servlet的幾種方式實例
本文分別給出了javascript發(fā)送請求到servlet的5種方式實例與 jsp發(fā)送請求到servlet的6種方式實例2018-03-03使用Springboot實現(xiàn)word在線編輯保存
PageOffice目前支持的Web編程語言及架構(gòu)有:Java(JSP、SSH、MVC等),ASP.NET(C#、VB.NET、MVC、Razor等),PHP,ASP,本篇文章就帶你使用Springboot整合PageOffice實現(xiàn)word在線編輯保存2021-08-08MyBatis-plus報錯Property ‘sqlSessionFactory‘ or 
這篇文章主要給大家介紹了MyBatis-plus 報錯 Property ‘sqlSessionFactory‘ or ‘sqlSessionTemplate‘ are required的兩種解決方法,如果遇到相同問題的朋友可以參考借鑒一下2023-12-12RestTemplate設(shè)置超時時間及返回狀態(tài)碼非200處理
這篇文章主要為大家介紹了RestTemplate設(shè)置超時時間及返回狀態(tài)碼非200處理,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06springboot 在idea中實現(xiàn)熱部署的方法
這篇文章主要介紹了springboot 在idea中實現(xiàn)熱部署的方法,實現(xiàn)了熱部署,在每一次作了修改之后,都會自動的重啟,非常節(jié)約時間,感興趣的小伙伴們可以參考一下2018-10-10Java基于Javafaker生成測試數(shù)據(jù)
這篇文章主要介紹了Java基于Javafaker生成測試數(shù)據(jù)的方法,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-12-12