我试图在序列化之前加密密码
我在下面的代码中得到 OptionalDataException。我读了很多文章,例如“之前读取非瞬态变量,程序中的 EOF,以与您在文件中写入相同的方式读取等.. 但本文没有解决我的问题,这是我遇到错误的程序。
class MySerialization implements Serializable{
public String username;
public transient String password;
public MySerialization(){
}
public MySerialization(String pass,String user){
this.password=pass;
this.username=user;
}
public String getPassword(){
return this.password;
}
//Write CustomObject in file
private void writeObject(ObjectOutputStream oos) throws Exception{
oos.defaultWriteObject();
String pass= "HAS"+password;
oos.writeChars(pass);
}
private void readObject(ObjectInputStream ois) throws Exception{
ois.defaultReadObject();
String pass= (String)ois.readObject(); //Here getting Exception OptionalDataException
password= pass.substring(3);
}
public String getUsername(){
return this.username;
}
}
class MyTest {
public static void main(String args[]) throws Exception{
MySerialization my1=new MySerialization("123456","User1");
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("n.txt"));
oos.writeObject(my1);
oos.close();
MySerialization my2=new MySerialization();
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("n.txt"));
my2=(MySerialization )ois.readObject();
System.out.println(my2.getUsername() +" "+my2.getPassword());
ois.close();
}
}