簡體   English   中英

在Android版Java中將點的ArrayList存儲到文件中

[英]Storing ArrayList of Points to a file in Java for Android

我無法將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();
    }

序列化 List<Point> ,您的Point類必須可序列化

public class Point implements Serializable {...}

我建議使用JSON( gson )API直接讀取和寫入對象。

可以將每個Point添加兩個Integer ,而不是將Point保留在ArrayList中。 整數支持SerializablePoint不支持。

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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM