简体   繁体   English

如何在Android中进行序列化和反序列化?

[英]How to serialize and deserialize in android?

my mainActivity has a ListView which should display my CustomList: 我的mainActivity有一个ListView,应该显示我的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. 我的问题是如何正确指向我的data.dat文件。 Thanks in advance 提前致谢

You can't write into the res directory (that's read-only), you have to write to somewhere else, eg to the cache directory (if it's only temporary; use context.getCacheDir() to get it's location) or to some permanent space (eg context.getFilesDir() ). 您无法写入res目录(只读),而必须写入其他地方,例如写入缓存目录(如果只是临时的;请使用context.getCacheDir()来获取其位置)或某个永久目录空间(例如context.getFilesDir() )。

You can get the file location like this, what you can pass to the FileOutputStream's or the FileInputStream's constructor: 您可以像这样获取文件位置,并将其传递给FileOutputStream或FileInputStream的构造函数:

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 在此处阅读有关在Android中存储文件的更多信息: http : //developer.android.com/training/basics/data-storage/files.html

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

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