user3431530
user3431530

Reputation: 1

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

I am trying to encrypt password before serialization
I am getting OptionalDataException in the following code. I read many article like "read non transient variable before , EOF in program, read in same way as you write in file etc .. but non of this article solving my problem here are following program where i am getting error.

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

Upvotes: 0

Views: 59

Answers (1)

käyrätorvi
käyrätorvi

Reputation: 381

You need to write/read the same types and in the same order. Currently you're writing char's so you should also be reading char's.

One example (also read 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);
}

Second example (write Object):

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

Upvotes: -1

Related Questions