2012-08-29 27 views
1

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

你可以分享你的異常的'stacktrace'? – Sujay

+0

您是否定義了自己的Point類?或者你使用內置的java Point類? – 2012-08-29 07:19:08

+0

@Remdroid - 我正在使用內置類 – Prasoon

回答

1

除了在ArrayList中保留Point之外,您還可以爲每個點添加兩個Integer。整數支持Serializable,Point不支持。

+0

是的,整數它的工作。謝謝。 – Prasoon

3

要seralize的List<Point>,你Point類必須serializable

public class Point implements Serializable {...} 

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

+0

android.graphics.Point不是Serializable。 –

+0

我正在使用內置的Point類。 – Prasoon

+0

這就是爲什麼我建議使用gson(JSON)API。 – adatapost

0

android.graphics.Point不是Serializable

創建一個新的類PointSerializable將在複製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; 
    } 
} 
+0

這會起作用,但上次我嘗試的時候對性能有很大的影響。如果表現不重要,那麼沒有問題。 –

相關問題