【问题标题】:Json is not being written to fileJson 没有被写入文件
【发布时间】:2019-11-19 16:27:18
【问题描述】:

我从 editText 获取输入并尝试将其文本写入 json 文件。当我执行代码时,它可以正常工作。但是当我再次尝试读取 json 文件时,它没有以前写入的对象。

我尝试过使用不同的编写器,例如 BufferedWriter、FileWriter。它们都不起作用。

这是 writeToJsonFile 方法


void writeJsonFile(TextView textView) {
        String json;
        try {
            InputStream is = context.getAssets().open("chores.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            if (is.read(buffer) == -1) {
                throw new EOFException();
            }
            is.close();
            json = new String(buffer, StandardCharsets.UTF_8);

            JSONObject obj = new JSONObject(json);
            JSONObject m_jArray = obj.getJSONObject("chores");
            JSONArray jsonArray = m_jArray.getJSONArray(title);

            JSONObject new_jobj = new JSONObject();
            new_jobj.put("task", textView.getText());
            new_jobj.put("isCompleted", false);

            jsonArray.put(new_jobj);

            File file = new File(context.getExternalFilesDir("/assets"), "chores.json");
            writeJsonFile(file, obj);
            Log.i("Done => ", "Written to file");


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

这个函数接受一个文件和一个json对象并将json对象写入文件


public static void writeJsonFile(File file, JSONObject json) throws IOException {
    FileWriter fileWriter = new FileWriter(file);
    fileWriter.write(json.toString());
    if (fileWriter != null) {
        fileWriter.close();
    }
}

我希望它将json字符串写入文件,但是下次我用InputStream再次读取文件时,它不会显示之前添加的Object。

预期的家务.json

{
  "chores": {
    "Daily": [
      {
        "task": "Task 1",
        "isCompleted": false
      }

    ],
    "Weekly": [

    ],
    "Monthly": [

    ],
    "Custom": [

    ]
  }
}

生成的 json

{
  "chores": {
    "Daily": [

    ],
    "Weekly": [

    ],
    "Monthly": [

    ],
    "Custom": [

    ]
  }
}

【问题讨论】:

  • 您必须将 jsonArray 写入 JSONObject,然后将该 JSONObject 写入文件。
  • @SriAji JSON 数组已经在 json 对象中。我还需要把它放在obj中吗?它不会向对象添加一个新数组吗?我想将对象添加到现有数组中。
  • 你没有添加 'jsonArray' 到任何东西。
  • 您确定它没有出现任何异常吗?你能检查你的logcat并在这里报告吗?我认为它引发了一个异常,该异常被您的 catch 块捕获并且没有使应用程序崩溃。
  • 可能是你正在创建新文件,检查文件路径

标签: java android json file filewriter


【解决方案1】:

您可以在 FileWriter 构造函数中使用 append 属性。你可以试试看。

FileWriter fileWriter = new FileWriter(file,true);

【讨论】:

    【解决方案2】:

    您没有将新创建的对象写入文件:例如:

            ...
            JSONObject new_jobj = new JSONObject();
            new_jobj.put("task", textView.getText());
            new_jobj.put("isCompleted", false);
    
            jsonArray.put(new_jobj);
    
            File file = new File(context.getExternalFilesDir("/assets"), "chores.json");
            // here instead of old obj write newly created new_jobj to file.
    
            writeJsonFile(file, new_jobj);
            Log.i("Done => ", "Written to file");
            ...
    

    【讨论】:

    • 这将使 json 文件只有新的 json 对象,不是吗?我想将它添加到json文件中的数组中。
    • 此外,调试器显示 obj 中包含 new_jobj。
    • 那么你需要修改旧的json obj 并重写它。
    • 如你所见,我也在做同样的事情。
    • 好吧,您没有更新以前的对象。比如:将新创建的jsonArray 放回obj。尝试将jsonArray 放入obj,您的问题应该会解决。
    【解决方案3】:

    在此之前,请确保您拥有 read and write storage permisions....

    Ex.

    try 
    {
        Writer output = null;
        File file = new File("filePath");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (!file.exists()) {
            file.createNewFile();
        }
        output = new BufferedWriter(new FileWriter(file));
        output.write(jsonObject.toString());
        output.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    

    【讨论】:

    • 试过了,没用。并且我已经授予了读写权限。
    • @KoushikBhargava 确保记录 jsonObject 数据是否存在并检查是否创建了目录文件
    • 当我转到我的 android 设备中 assets 文件夹的路径时,它没有显示 chores.json 文件
    • @KoushikBhargava 在写入文件之前检查文件是否存在,如果存在则记录文件路径
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    相关资源
    最近更新 更多