1

我无法将 ArrayList 写入文件。我正在做以下事情,正确的方法是什么?
如果我不将 'pt' 添加到 arraylist 中,则过程会正常并被保存。
os.writeObject(arr); - 在这一行之后,调试器转到 IOException。代码:

//holder class implements Serializable
transient ArrayList<Point> arr;
transient Point pt;
//I've tried without transient, same result 
//
arr = new ArrayList<Point>();
pt = new Point();
p.x = 10;
p.y = 20;
arr.add(pt);
//If I don't add 'pt' into arraylist, process goes fine and it gets saved.
//
String strStorageDirectory = this.getFilesDir() + "/DataFiles";
final File DataStorageDirectory = new File(strStorageDirectory);
File lfile = new File(DataStorageDirectory, "samplefile.bin");
FileOutputStream fos;
    try {
        fos = new FileOutputStream(lfile);
        ObjectOutputStream os = new ObjectOutputStream(fos);
        os.writeObject(arr);//after this line debugger goes to IOException
        //I've tried with os.writeObject((Serializable)arr), same result;
        os.flush();//I've tried removing it, same result
        os.close();
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
4

3 回答 3

3

要序列化List<Point>​​,您的Point类必须是可序列化的。

public class Point implements Serializable {...}

我建议使用 JSON ( gson ) API 直接读取和写入对象。

于 2012-08-29T07:20:39.470 回答
1

您可以在每个点添加两个Integer ,而不是将Point保留在 ArrayList 中。Integer 支持Serializable,不支持。Point

于 2012-08-29T07:21:19.250 回答
1

android.graphics.Point不是Serializable

Point Serializable创建一个将复制android.graphics.Point到自定义Point类的新类

class Point implements Serializable
{
    private static final long serialVersionUID = 1L;

    private int x;
    private int y;

    Point(android.graphics.Point point)
    {
        this.x  = point.x;
        this.y= point.y;
    }
}
于 2012-08-29T07:24:12.463 回答