2010-05-21 3 views
0

우리는 비 직렬화를 사용하여 파일 (.dat)에서 데이터를 동적으로 읽어야하는 응용 프로그램이 있습니다. 우리는 실제로 첫 번째 객체를 가져오고 "for"루프를 사용하여 다른 객체에 액세스 할 때 null 포인터 예외와 "java.io.StreamCorruptedException : 잘못된 유형 코드 : AC"를 발생시킵니다.추가 모드에서 파일 (.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

은 다음과 같습니다. http://stackoverflow.com/questions/2879726/retrieve-data-from-dat-file – JoseK

답변

0

. (전 OIS에서 읽지 않고)

시도 :이 가진 파일을 만들 APPEND 옵션 (new FileOutputStream(file,true);)를 사용하여

stream: 
    magic version contents 

: 직렬화 된 객체에 대한

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

grammar는 다음과 같이 정의된다 데이터 :

stream: 
    magic version contents magic version contents magic version contents .... 

이 데이터는 사양에 따라 다르므로 ObjectInputStream으로 디코딩 할 수 없습니다.

관련 문제