国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

JAVA 格式化JSON數(shù)據(jù)并保存到j(luò)son文件中的實(shí)例

瀏覽:2日期:2022-08-22 15:40:21

使用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)。

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 南京市| 渭源县| 视频| 九龙坡区| 南宁市| 阿巴嘎旗| 龙海市| 外汇| 宜春市| 靖西县| 芮城县| 大城县| 繁峙县| 玉林市| 德江县| 邵阳县| 大城县| 永川市| 钟山县| 天气| 育儿| 汤原县| 松滋市| 湛江市| 永平县| 寻甸| 汉阴县| 米易县| 阳山县| 西宁市| 庆城县| 乐业县| 赤峰市| 岳普湖县| 秦皇岛市| 保康县| 襄垣县| 嵊泗县| 普兰县| 霞浦县| 崇信县|