2015-03-13 53 views
-1

我試圖將一個對象存儲到數據文件,並且我可以創建該文件,但是當我嘗試追加任何文件時,它只是創建一個新文件並覆蓋舊的文件。Android:不能附加到ObjectOutputFile

我創建代碼:

public void createObject(Object object) 
{ 

    //File outFile = new File(Environment.getExternalStorageDirectory(), "foobar.data"); 
    try 
    { 

     File outFile = new File(Environment.getExternalStorageDirectory(), "foobar.data"); 
     ObjectOutput out = new ObjectOutputStream(new FileOutputStream(outFile)); 
     out.writeObject(object); 
     out.close(); 
    } 
    catch (IOException e) 
    { 
     Log.i("CreateObject", "Write - Catch error can't find .data"); 
    } 
    finally 
    { 
     try 
     { 
      // out.close(); 
      Log.i("CreateObject", "Closed successfully!"); 
     } 
     catch (Exception e) 
     { 
      Log.i("CreateObject", "Write - Failed to close object output stream."); 
     } 
    } 

我嘗試使用代碼在https://docs.oracle.com/javase/8/docs/api/java/io/ObjectInputStream.html

FileOutputStream fos = new FileOutputStream("foobar.data"); 
ObjectOutputStream oos = new ObjectOutputStream(fos); 
oos.writeObject(event); 
oos.close(); 

取代了我的try但我的程序直接進到catch。捕捉錯誤是java.io.FileNotFoundException: /foobar.data: open failed: EROFS (Read-only file system)

回答

0

new FileOutputStream(...)有一個附加參數。如果你不使用它,或者不把它設置爲true,你會得到一個新的文件。

但是無論如何這不會起作用。你不能附加到對象流,至少不採取特殊措施。當你讀到它時你會得到的是StreamCorruptedException: invalid type code AC