2010-05-21 6 views
0

Nous avons une application qui nous oblige à lire dynamiquement les données d'un fichier (.dat) en utilisant la désérialisation. Nous obtenons en fait le premier objet et il jette une exception de pointeur nul lorsque nous accédons à d'autres objets en utilisant une boucle "for".Récupérer des données à partir du fichier .dat

  File file=null; 
      FileOutputStream fos=null; 
      BufferedOutputStream bos=null; 
      ObjectOutputStream oos=null; 
      try{ 
       file=new File("account4.dat"); 
       fos=new FileOutputStream(file,true); 
       bos=new BufferedOutputStream(fos); 
       oos=new ObjectOutputStream(bos); 
       oos.writeObject(m); 
       System.out.println("object serialized"); 
       amlist=new MemberAccountList(); 
       oos.close(); 
      } 
      catch(Exception ex){ 
      ex.printStackTrace(); 
      } 

objets de lecture:

try{ 
     MemberAccount m1; 
     file=new File("account4.dat");//add your code here 
     fis=new FileInputStream(file); 
     bis=new BufferedInputStream(fis); 
     ois=new ObjectInputStream(bis); 
     System.out.println(ois.readObject()); 
     **while(ois.readObject()!=null){ 
     m1=(MemberAccount)ois.readObject(); 
      System.out.println(m1.toString()); 
     }/*mList.addElement(m1);** // Here we have the issue throwing null pointer exception 
     Enumeration elist=mList.elements(); 
     while(elist.hasMoreElements()){ 
      obj=elist.nextElement(); 
      System.out.println(obj.toString()); 
     }*/ 

    } 
    catch(ClassNotFoundException e){ 

    } 
    catch(EOFException e){ 
     System.out.println("end"); 
    } 
    catch(Exception ex){ 
     ex.printStackTrace(); 
    } 
+0

double possible [Comment lire les données du fichier (.dat) en mode append] (http://stackoverflow.com/questions/2880498/how-to -read-data-from-file-dat-en-append-mode) – McDowell

Répondre

1

Le problème est votre boucle while:

while(ois.readObject()!=null){ 
    m1=(MemberAccount)ois.readObject(); 
    System.out.println(m1.toString()); 
} 

Vous lisez un objet de flux, vérifier si elle est non nulle, puis lire à nouveau du courant. Maintenant, le flux peut être vide en retournant null.

Vous pouvez le faire à la place:

while(ois.available() > 0){ 
    m1=(MemberAccount)ois.readObject(); 
    System.out.println(m1.toString()); 
} 
Questions connexes