2014-02-11 191 views
0

我從文件Java中讀取對象時遇到問題。從文件讀取對象

filearraylist<projet>

這是保存對象的代碼:

try { 
    FileOutputStream fileOut = new FileOutputStream("les projets.txt", true); 
    ObjectOutputStream out = new ObjectOutputStream(fileOut); 

    for (projet a : file) { 
     out.writeObject(a); 
    } 
    out.close(); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

這是閱讀的對象從文件::寫作正常工作的代碼

try { 
    FileInputStream fileIn = new FileInputStream("les projets.txt"); 
    ObjectInputStream in = new ObjectInputStream(fileIn); 

    while (in.available() > 0){ 
     projet c = (projet) in.readObject(); 

     b.add(c); 
    } 

    choisir = new JList(b.toArray()); 
    in.close(); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

。問題是閱讀......它不讀任何對象(projet)可能是什麼問題?

+0

嗨,你有沒有得到你的代碼的'e.printStackTrace()'行打印的任何異常消息?如果是這樣,請你將跟蹤貼到問題上。 – mico

+0

sry我有編輯我的問題cz任何對象重新註冊! – user3285843

+0

@mico noo打印任何異常消息 – user3285843

回答

0

正如EJP在評論中提到的和this SO post。如果您打算在單個文件中編寫多個對象,則應編寫自定義ObjectOutputStream,因爲在寫入第二個或第n個對象頭信息時,該文件將被損壞。
正如EJP建議寫爲ArrayList,由於ArrayList已經是Serializable,所以你不應該有問題。作爲

out.writeObject(file)並重新讀取爲ArrayList b = (ArrayList) in.readObject();
由於某種原因,如果你不能把它寫成ArrayList中。創建custome ObjectOutStream爲

class MyObjectOutputStream extends ObjectOutputStream { 

public MyObjectOutputStream(OutputStream os) throws IOException { 
    super(os); 
} 

@Override 
protected void writeStreamHeader() {} 

}

,改變你的writeObject作爲

try { 
     FileOutputStream fileOut= new FileOutputStream("les_projets.txt",true); 
     MyObjectOutputStream out = new MyObjectOutputStream(fileOut); 

     for (projet a : file) { 
    out.writeObject(a); 
} 
     out.close(); 
    } 

    catch(Exception e) 
    {e.printStackTrace(); 

}

,改變你的readObject作爲

ObjectInputStream in = null; 
    try { 
     FileInputStream fileIn = new FileInputStream("C:\\temp\\les_projets1.txt"); 
     in = new ObjectInputStream(fileIn); 

     while(true) { 
      try{ 
       projet c = (projet) in.readObject(); 
       b.add(c); 
      }catch(EOFException ex){ 
       // end of file case 
       break; 
      } 

     } 

    }catch (Exception ex){ 
     ex.printStackTrace(); 
    }finally{ 
     try { 
      in.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
+0

關閉時出錯() potentiel.java:263:錯誤:未報告的異常IOException;必須被捕獲或被宣佈爲拋出 \t \t \t \t ex.printStackTrace(); } finally {in.close(); } – user3285843

+0

在讀取對象的finally塊中應該添加try catch。我修改了代碼。 – Mani

+0

使用try-with-resources來處理關閉流。 – Pshemo