【发布时间】:2018-02-26 00:39:35
【问题描述】:
我最近为用户制作了一个串行文件。当用户尝试登录时,我会读取它。如果新用户注册,则将用户添加到其中。但是每当我添加一个新用户时,我添加的以前的记录都会被删除。有没有办法将对象附加到串行文件? P.S 我使用包含用户名、密码、角色(教师或学生)和分数(int)变量的用户对象。
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.");
}
}
【问题讨论】:
-
也发布您的代码
-
您需要将其作为问题的一部分发布,而不是作为评论发布
-
完成,新网站。
-
什么是 openFile 方法?
-
两种方法都添加到代码中
标签: java serialization deserialization file-handling persistent-storage