要在Java中新增一个JSON文件到本地,可以按照以下步骤进行操作:

  1. 导入相关的Java库:
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONObject;
  1. 创建一个JSONObject对象,并添加需要保存的数据:
JSONObject json = new JSONObject();
json.put("name", "John");
json.put("age", 30);
json.put("city", "New York");
  1. 使用FileWriter将JSONObject写入文件:
try (FileWriter file = new FileWriter("path/to/file.json")) {
   file.write(json.toJSONString());
   file.flush();
} catch (IOException e) {
   e.printStackTrace();
}

请将 "path/to/file.json" 替换为你想要保存JSON文件的路径和文件名。

完整的代码如下:

import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONObject;

public class Main {
   public static void main(String[] args) {
      JSONObject json = new JSONObject();
      json.put("name", "John");
      json.put("age", 30);
      json.put("city", "New York");

      try (FileWriter file = new FileWriter("path/to/file.json")) {
         file.write(json.toJSONString());
         file.flush();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

运行该代码后,将在指定的路径下创建一个名为 file.json 的JSON文件,并将数据写入该文件中

Java新增一个json文件到本地

原文地址: https://www.cveoy.top/t/topic/iNoy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录