1. 创建一个 JSONObject 对象,并将数组转换为 JSON 格式的字符串:
JSONObject json = new JSONObject();
json.put('myArray', new JSONArray(Arrays.asList(myArray)));
String jsonString = json.toString();
  1. 将 JSON 字符串写入文件:
FileOutputStream outputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(jsonString.getBytes());
outputStream.close();

其中,filename 是要保存的文件名,Context.MODE_PRIVATE 表示以覆盖原文件的模式打开文件。

完整代码示例:

public void saveArrayToFile(Context context, String filename, String[] myArray) {
    try {
        // Convert array to JSON string
        JSONObject json = new JSONObject();
        json.put('myArray', new JSONArray(Arrays.asList(myArray)));
        String jsonString = json.toString();

        // Write JSON string to file
        FileOutputStream outputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
        outputStream.write(jsonString.getBytes());
        outputStream.close();
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Android 保存数组为 JSON 文件:覆盖模式

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

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