我無法將ArrayList寫入文件。我在做以下事情,正確的方法是什麼?
如果我沒有將「pt」添加到arraylist中,過程就會正常進行並保存。
os.writeObject(arr); - 此行調試器進入IOException後。代碼:將ArrayList的點存儲到Java中的Android文件中
//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();
}
你可以分享你的異常的'stacktrace'? – Sujay
您是否定義了自己的Point類?或者你使用內置的java Point類? – 2012-08-29 07:19:08
@Remdroid - 我正在使用內置類 – Prasoon