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.");
}
}
發佈你的代碼也 – Ravi
你需要發佈它作爲你的問題的一部分,而不是作爲評論 – Ravi
完成,新的網站。 –