0

최근에 사용자를 위해 직렬 파일을 만들었습니다. 사용자가 로그인하려고 할 때 읽은 사용자. 새 사용자가 등록하면 사용자를 추가 할 수 있습니다. 그러나 새 사용자를 추가 할 때마다 내가 추가 한 이전 레코드가 삭제됩니다. 직렬 파일에 객체를 추가하는 방법이 있습니까? P.Sim 사용자 이름, 비밀번호, 역할 (강사 또는 학생) 및 점수 (int) 변수를 포함하는 사용자의 개체를 사용합니다.직렬화 : Java에서 객체 파일에 추가

public static void addRecordStudent(String userName, String password, String role, int score) 
{ 
    openFile(); 
    try 
    { 
     // create new record; this example assumes valid input 
     User usr = new User(userName, password, role, score); 
     // serialize record object into file 
     output.writeObject(usr); 
    } 
    catch (NoSuchElementException elementException) 
    { 
     System.err.println("Invalid input. Please try again."); 
    } 
    catch (IOException ioException) 
    { 
     System.err.println("Error writing to file. Terminating."); 
    } 
    closeFile(); 
} 

public static void openFile() 
{ 
    try 
    { 
     output = new ObjectOutputStream(Files.newOutputStream(Paths.get("users.ser"))); 
    } 
    catch (IOException ioException) 
    { 
     System.err.println("Error opening file. Terminating."); 
     System.exit(1); // terminate the program 
    } 
} 

public static void closeFile() 
{ 
    try 
    { 
     if (output != null) 
     output.close(); 
    } 
    catch (IOException ioException) 
    { 
     System.err.println("Error closing file. Terminating."); 
    } 
} 
+0

코드도 게시하십시오 – Ravi

+0

질문의 일부로 의견을 게시 하시려면 – Ravi

+0

완료, 사이트를 처음 방문해야합니다. –

답변

0

명시 적으로 파일에 추가하도록 선택해야합니다 - 그렇지 않으면 기존 내용이 대체됩니다 :

Files.newOutputStream (파일, StandardOpenOption.APPEND)

그 외에도, 때마다 새로운 ObjectOutputStream의 새로운 생성 스트림이 시작됩니다. 단일 ObjectInputStream을 사용하여 다시 읽을 수는 없습니다. this trick

파일이 너무 크지 않은 경우 모든 기존 개체를 읽고 단일 ObjectOutputStream을 사용하여 기존 개체와 새 개체를 다시 쓰는 것이 좋습니다.