我在以下程序中得到OptionalDataException。为什么会出现此错误

时间:2019-05-03 07:49:44

标签: java serialization optionaldataexception

我正在尝试在序列化之前对密码进行加密
  我在以下代码中得到OptionalDataException。     我读了很多文章,例如“之前读过非瞬时变量,     程序,以与写入文件等相同的方式读取。     但不是本文解决我的问题 以下是我遇到错误的程序。

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();
  }
}

1 个答案:

答案 0 :(得分:-1)

您需要以相同的顺序写/读相同的类型。当前,您正在写char,因此也应该阅读char

一个示例(另请参见char):

private void readObject(ObjectInputStream ois) throws Exception{
    ois.defaultReadObject();
    StringBuilder passBuilder = new StringBuilder();
    try {
        while (true) {
            passBuilder.append(ois.readChar());
        }
    } catch (EOFException e) {
        // Reached end of stream.
    } finally {
        ois.close();
    }
    String pass = passBuilder.toString();
    password = pass.substring(3);
}

第二个示例(写Object):

private void writeObject(ObjectOutputStream oos) throws Exception{
    oos.defaultWriteObject();
    String pass= "HAS"+password;
    oos.writeObject(pass);
}