简体   繁体   English

Android 内部存储:文件一旦被读取即为空

[英]Android Internal Storage: File is empty as soon as it has been read

So I am trying to save a HashMap as a JSON file into the internal storage of the app.所以我试图将 HashMap 作为 JSON 文件保存到应用程序的内部存储中。 This works well, as I can see in the device file explorer, everything is saved properly.这很有效,正如我在设备文件资源管理器中看到的那样,所有内容都已正确保存。 When I then restart the app and read from the file it also works BUT after this one time reading the file is empty.当我重新启动应用程序并从文件中读取时,它也可以工作,但是在这一次读取文件为空之后。 Completely empty not even some "{}" when you save an empty JSON object.当您保存一个空的 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();
    }
}

Any ideas?有任何想法吗?

I actually found a way for it to work... I am now calling writeNetowrks(..) in the onStop() method of my activity.我实际上找到了一种工作方式......我现在在我的活动的onStop()方法中调用writeNetowrks(..) It seems to work consistent so far.到目前为止,它似乎工作一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM