【问题标题】:I am getting OptionalDataException in the following Program. why this error is coming我在以下程序中得到 OptionalDataException。为什么会出现这个错误
【发布时间】:2019-05-03 07:49:43
【问题描述】:

我正在尝试在序列化之前加密密码
我在下面的代码中得到 OptionalDataException。 我读过很多文章,例如“之前读取非瞬态变量,EOF in 程序,读取方式与写入文件等相同。 但这篇文章没有解决我的问题 以下是我遇到错误的程序。

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

【问题讨论】:

  • 你正在读取一个对象,所以你应该写一个对象。仅仅在前面加上“HAS”并不构成任何形式的加密。

标签: java serialization optionaldataexception


【解决方案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);
}

【讨论】:

  • available() 的使用不正确。并不是说有很多。或任何。
  • 重新编辑,使用read/writeObject()read/writeUTFChars() 会简单得多,争议更少,效率更高。
猜你喜欢
  • 2019-01-25
  • 2021-11-28
  • 2019-04-17
  • 2021-11-08
  • 1970-01-01
  • 2021-09-05
  • 2018-09-22
  • 2016-11-25
  • 1970-01-01
相关资源
最近更新 更多