How to serialize and deserialize in android?

烈酒焚心 提交于 2021-01-29 07:30:58

问题


my mainActivity has a ListView which should display my CustomList:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

public class CustomList implements Serializable {
    private static final long serialVersionUID = 1L;
    private ArrayList<Game> list = new ArrayList<Game>();
    public void add(Game toAdd){
        list.add(toAdd);
    }
    public Game get(int id){
        return list.get(id);
    }
    public ArrayList<Game> getList(){
        return list;
    }
    public void serialize(){
        try {
            FileOutputStream fo = new FileOutputStream("res\\data.dat");
            ObjectOutputStream ou = new ObjectOutputStream(fo);
            ou.writeObject(list);
            ou.close();
            fo.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void deserialize(){
        try {
            FileInputStream fi = new FileInputStream("res\\data.dat");
            ObjectInputStream oi = new ObjectInputStream(fi);
            list = (ArrayList<Game>)oi.readObject();
            oi.close();
            fi.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

I get the following error trying to serialize or desirialize:

java.io.FileNotFoundException: res\data.dat: open failed: ENOENT (No such file or directory)

My question is how to proper point to my data.dat file. Thanks in advance


回答1:


You can't write into the res directory (that's read-only), you have to write to somewhere else, e.g. to the cache directory (if it's only temporary; use context.getCacheDir() to get it's location) or to some permanent space (e.g. context.getFilesDir()).

You can get the file location like this, what you can pass to the FileOutputStream's or the FileInputStream's constructor:

File file = new File(context.getFilesDir(), "data.dat");

You may also have to request permission to write to external storage if you choose so.

Read more about storing files in Android here: http://developer.android.com/training/basics/data-storage/files.html



来源:https://stackoverflow.com/questions/33054035/how-to-serialize-and-deserialize-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!