簡體   English   中英

我在以下程序中得到OptionalDataException。 為什么會出現此錯誤

[英]I am getting OptionalDataException in the following Program. why this error is coming

我正在嘗試在序列化之前加密密碼
我在以下代碼中得到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();
  }
}

您需要以相同的順序寫/讀相同的類型。 目前,您正在寫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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM