2010-05-21 2 views
0

우리는 파일에서 데이터 (.dat)를 역 직렬화를 사용하여 동적으로 읽어야하는 애플리케이션이 있습니다. 실제로 첫 번째 객체를 가져오고 "for"루프를 사용하여 다른 객체에 액세스 할 때 null 포인터 예외가 발생합니다..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(); 
      } 

독서 객체 :

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

가능한 중복 [추가 모드 파일 (.DAT)에서 데이터를 읽는 방법] (http://stackoverflow.com/questions/2880498/how-to -read-data-from-append-mode) – McDowell

답변

1

을 문제는 당신의 while 루프입니다 :

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

당신은 null가 아닌 있는지 확인하고 다시 읽어 스트림에서 개체를 읽고 스트림에서. 이제 스트림은 null을 반환하는 비어있을 수 있습니다.

대신이 작업을 수행 할 수 있습니다 :

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