欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2020年10月19日 09:48:12   作者:長(zhǎng)谷平川獨(dú)留衣  
這篇文章主要介紹了JAVA 格式化JSON數(shù)據(jù)并保存到j(luò)son文件中的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

使用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è)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論