2012-08-02 82 views
0

我知道這個主題有一些問題需要回答,但我需要更具體的幫助,因爲這是我第一次嘗試這樣的事情。我試圖實現這些問題的答案,但仍然有錯誤。我需要將一個動態數量的序列化對象寫入文件,然後從該文件中讀取以檢索對象。我正在使用android的FYI。覆蓋writeStreamHeader()將序列化對象附加到單個文件

這是我寫()和重載writeStreamHeader():

//check and see if there is a file already created to hold patterns, if not, make one 
//only created once or if file is deleted; append to it if it's already created 
    if(!new File(getFilesDir()+"/Patterns").exists()) 
     { 
      try { 
       fos = new FileOutputStream(getFilesDir()+FILENAME, true); 
       out = new ObjectOutputStream(fos); 
       } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      } 
     } 
     else 
     { 
     try { 
      out = new AppendingObjectOutputStream(fos); 
      } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      } 
     } 

     //create a pattern of points. Max amount of Patterns is 100. 
        if(patternindex!=100) 
        { 
         Patterns[patternindex] = new Pattern(ActivePoints, name, xshift, yshift, scaling, rotation); 
         try { 
          //out.reset(); 
          out.writeObject(Patterns[patternindex]); //write the object 
          //out.close(); 
         } catch (IOException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 
         patternindex++; 
         dialog.dismiss(); 
        } 

public class AppendingObjectOutputStream extends ObjectOutputStream { 

     public AppendingObjectOutputStream(OutputStream out) throws IOException { 
     super(out); 
     } 
     @Override 
     protected void writeStreamHeader() throws IOException { 
      out.reset(); 
     // do not write a header 
     } 

    } 

我請檢查該文件是否存在(它,因爲我碰到這個代碼),然後我的writeObject()導致程序崩潰在創建「特殊」ObjectOutputStream後發生NULLPointerException異常。

這裏是我的反序列化/讀取:

String PatternNames[] = new String[2]; 
Pattern Patterns[] = new Pattern[2]; 
FileInputStream fis; 
ObjectInputStream in; 

try { 
      fis = new FileInputStream(getFilesDir()+"/Patterns"); 
      in = new ObjectInputStream(fis); 

      for(int i=0;i<2;i++)//just trying to read 2 objects to start with 
      { 
       { 
        Patterns[i] = (Pattern) in.readObject(); 
        PatternNames[i] = Patterns[i].getName(); 
       } 


      } 
      in.close(); 
     } catch (ClassNotFoundException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
     catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
       } 

任何幫助是極大的讚賞,因爲我已經花了很多時間相當試圖弄清楚這一點。我知道有些人已經完成了整個工作。作爲一個方面說明,我已經獲得序列化/反序列化處理一個對象保存到不同的文件,但這是最沒有用的,因爲我的項目需求。

+0

發佈堆棧跟蹤。 – EJP 2012-08-05 09:49:14

回答

0

您只在文件不存在的情況下構建fos。在這兩種情況下都需要它。