[英]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();
}
可以將每個Point添加兩個Integer ,而不是將Point保留在ArrayList中。 整數支持Serializable , Point
不支持。
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.