2011-10-30 3 views
0

serialastion을 사용하여 이진 파일에 arrayList를 저장했습니다. 어떻게이 이진 파일에서이 데이터를 검색합니까? 에서 선언 된 배열 목록Java의 이진 파일에서 데이터의 ArrayList를 deserialize하는 방법은 무엇입니까?

public void readInSerialisable() throws IOException 
{ 
    FileInputStream fileIn = new FileInputStream("theBKup.ser"); 

    ObjectInputStream in = new ObjectInputStream(fileIn); 

    try 
    { 
    ArrayList readob = (ArrayList)oi.readObject(); 
       allDeps = (ArrayList) in.readObject(); 
    } 
    catch (IOException exc) 
    { 
     System.out.println("didnt work"); 
    } 
} 

allDeps된다

내가 직렬화

public void createSerialisable() throws IOException 
{ 
    FileOutputStream fileOut = new FileOutputStream("theBkup.ser"); 
    ObjectOutputStream out = new ObjectOutputStream(fileOut); 
    out.writeObject(allDeps); 
    options(); 
} 

에 사용한 코드와 내가 ArrayList를 역 직렬화에 사용하는 것을 시도하고이 코드입니다 클래스 생성자. 이 클래스에서 선언 된 arrayList에 파일의 arrayList를 저장하려고합니다.

+0

무엇이 arraylist입니까? –

+0

부서 및 이름이 있습니다. – Binyomin

+0

그리고 'oi'는 무엇입니까? –

답변

1

코드는 대부분 정확하지만 한 가지 실수와 두 가지 점이 더 잘 작동 할 수 있습니다. 별표로 강조 표시했습니다. (분명히 '코드'모드에서 굵게 표시 할 수 없기 때문입니다.)

public void createSerialisable() throws IOException 
{ 
    FileOutputStream fileOut = new FileOutputStream("theBkup.ser"); 
    ObjectOutputStream out = new ObjectOutputStream(fileOut); 
    out.writeObject(allDeps); 
    **out.flush();** // Probably not strictly necessary, but a good idea nonetheless 
    **out.close();** // Probably not strictly necessary, but a good idea nonetheless 
    options(); 
} 

public void readInSerialisable() throws IOException 
{ 
    FileInputStream fileIn = new FileInputStream("theBKup.ser"); 

    ObjectInputStream in = new ObjectInputStream(fileIn); 

    try 
    { 
     **// You only wrote one object, so only try to read one object back.** 
     allDeps = (ArrayList) in.readObject(); 
    } 
    catch (IOException exc) 
    { 
     System.out.println("didnt work"); 
     **exc.printStackTrace();** // Very useful for findout out exactly what went wrong. 
    } 
} 

희망이 있습니다. 그래도 문제가 계속 표시되면 스택 추적과 문제를 보여주는 완전한 자체 포함 된 컴파일 가능한 예제를 게시하십시오.

allDeps에는 실제로 Serializable 인 개체가 포함되어 있고 createSerialisable이 아닌 readInSerialisable에 문제가 있다고 가정했습니다. 스택 추적은 매우 유용합니다.

+0

Cameron에게 감사드립니다. 그러나 여전히 컴파일되지 않습니다. 해당보고되지 않는 예외 ClassNotFound가 catch되거나 선언되어야합니다. 온라인 : allDeps1 = (ArrayList) in.readObject(); – Binyomin

+0

오. 컴파일 * 오류라고 언급하지 않았습니다. 간단하다.'try' 블록 다음에'catch (ClassNotFoundException e)'블록을 추가한다. 또는'catch (IOException exc)'를'catch (Exception exc)'로 변경하십시오. –

+0

도움을 주셔서 감사합니다. – Binyomin

관련 문제