如何在Android中进行序列化和反序列化? [英] How to serialize and deserialize in android?

查看:133
本文介绍了如何在Android中进行序列化和反序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的mainActivity有一个ListView,它应该显示我的CustomList:

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)

我的问题是如何正确指向我的data.dat文件.预先感谢

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

推荐答案

您无法写入res目录(只读),而必须写入其他位置,例如到缓存目录(如果只是临时目录,请使用 context.getCacheDir()以获取其位置)或某个永久性空间(例如

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()).

您可以获得这样的文件位置,可以将其传递给FileOutputStream或FileInputStream的构造函数:

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.

在此处详细了解有关在Android中存储文件的信息: http://developer.android.com/training/basics/data-storage/files.html

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

这篇关于如何在Android中进行序列化和反序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆