【问题标题】:Android Internal Storage: File is empty as soon as it has been readAndroid内部存储:文件一经读取就为空
【发布时间】:2020-07-10 00:11:29
【问题描述】:

所以我试图将 HashMap 作为 JSON 文件保存到应用程序的内部存储中。这很好用,正如我在设备文件资源管理器中看到的那样,所有内容都已正确保存。然后,当我重新启动应用程序并从文件中读取时,它也可以工作,但是在这一次读取文件为空之后。当您保存一个空的 JSON 对象时,完全清空甚至没有一些“{}”。

public void writeNetworks(FileOutputStream fos) {
    Log.d(TAG, "writeNetworks");

    Gson gson = new GsonBuilder().create();
    String json = gson.toJson(networks);

    Log.d(TAG, json);

    PrintWriter out = new PrintWriter(new OutputStreamWriter(fos));
    out.println(json);
    out.flush();
    out.close();
}

public void readNetworks(FileInputStream fis) {
    Log.d(TAG, "readNetworks");

    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(fis));
        StringBuilder json = new StringBuilder();
        String line;
        while((line = in.readLine()) != null ) {
            json.append(line);
        }
        in.close();

        Log.d(TAG, json.toString());

        Gson gson = new GsonBuilder().create();
        Type typeOfHashMap = new TypeToken<Map<String, WrcUser>>() { }.getType();
        networks = gson.fromJson(json.toString(), typeOfHashMap);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

有什么想法吗?

【问题讨论】:

标签: java android json file android-studio


【解决方案1】:

我实际上找到了一种工作方式......我现在在我的活动的onStop() 方法中调用writeNetowrks(..)。到目前为止,它似乎工作一致。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多