Java object can write into a file for future access, this is called serialization. In order to do this, you have to implement the Serializableinterface, and use ObjectOutputStream to write the object into a file.
Create an “User” object and implementSerializable interface. This object is going to write into a file.
packageorg.hello.io;
importjava.io.Serializable;
publicclass User implementsSerializable{
privatestaticfinallong serialVersionUID = 1L;
longid;
String username;
String password;
publiclonggetId(){
returnid;
}
publicvoidsetId(longid){
this.id=id;
}
publicStringgetUsername(){
return username;
}
publicvoidsetUsername(String username){
this.username = username;
}
publicStringgetPassword(){
return password;
}
publicvoidsetPassword(String password){
this.password = password;
}
@Override
publicStringtoString(){
returnnewStringBuffer("ID: ")
.append(this.id)
.append(" Username: ")
.append(this.username)
.append(" Password: ")
.append(this.password).toString();
}
}
The method serializeUser()will write the “User” object and it’s variable value(18,"Harry","pass") into a file named “user.ser”, locate in c drive.
The method deserializeUser() will read a serialized file “c:\\user.ser” – created in this example, and convert it back to “User” object and print out the saved value. 完整实例如下: