📜  在java中将json字符串写入文件(1)

📅  最后修改于: 2023-12-03 14:51:17.334000             🧑  作者: Mango

在 Java 中将 Json 字符串写入文件

在 Java 开发中,我们经常会遇到需要将 Json 字符串写入文件的场景,例如将 Json 数据存储到本地的配置文件中。下面介绍几种 Java 中将 Json 字符串写入文件的方法。

使用 Java 中的 FileWriter 和 BufferedWriter 类
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import org.json.JSONObject;

public class WriteJsonToFileExample {

  public static void main(String[] args) {

    String jsonStr = "{\"id\": \"001\",\"name\": \"John\",\"age\": 21}";

    try (BufferedWriter writer = new BufferedWriter(new FileWriter("data.json"))) {

      // 创建 JSON 对象
      JSONObject jsonObj = new JSONObject(jsonStr);

      // 将 JSON 对象写入文件
      writer.write(jsonObj.toString());

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
使用 Java 中的 FileOutputStream 和 PrintWriter 类
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import org.json.JSONObject;

public class WriteJsonToFileExample {

  public static void main(String[] args) {

    String jsonStr = "{\"id\": \"001\",\"name\": \"John\",\"age\": 21}";

    try (PrintWriter writer = new PrintWriter(new FileOutputStream("data.json"))) {

      // 创建 JSON 对象
      JSONObject jsonObj = new JSONObject(jsonStr);

      // 将 JSON 对象写入文件
      writer.println(jsonObj.toString());

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
使用 Java 中的 Files 类
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.json.JSONObject;

public class WriteJsonToFileExample {

  public static void main(String[] args) {

    String jsonStr = "{\"id\": \"001\",\"name\": \"John\",\"age\": 21}";

    try {
      // 创建 JSON 对象
      JSONObject jsonObj = new JSONObject(jsonStr);

      // 将 JSON 对象写入文件
      Files.write(Paths.get("data.json"), jsonObj.toString().getBytes());

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

以上就是几种 Java 中将 Json 字符串写入文件的方法,选择合适的方法根据自己的具体业务需求来决定。