0

我最近爲用戶製作了一個串行文件。我從用戶嘗試登錄時讀取的內容。如果新用戶註冊,則添加用戶。但是每當我添加一個新用戶時,我添加的上一條記錄被刪除。有沒有辦法將對象追加到串行文件? P.S Im使用包含用戶名,密碼,角色(教師或學生)和分數(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寫回現有對象和新對象可能會更好。