Java 如何将 JSON 数据写入本地文件
要在 Java 中新增一个 JSON 文件到本地,可以按照以下步骤进行操作:
- 导入相关的 Java 库:
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONObject;
- 创建一个 JSONObject 对象,并添加需要保存的数据:
JSONObject json = new JSONObject();
json.put('name', 'John');
json.put('age', 30);
json.put('city', 'New York');
- 使用 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 文件,并将数据写入该文件中。
原文地址: https://www.cveoy.top/t/topic/qtAE 著作权归作者所有。请勿转载和采集!