0

I am trying to read multiple '.dat' files one by one inside a specific folder. below is my code

public void viewEngingeer() throws Exception
    {
        File f = new File("Users");
        ArrayList<String> usersList = new ArrayList<String>(Arrays.asList(f.list()));

    int index=0;
    while (index < usersList.size()) { 
    User newUser=new User();
    FileInputStream fis = new FileInputStream("Users/"+usersList.get(index));
    ObjectInputStream ois =  new ObjectInputStream(fis);
    newUser = (User) ois.readObject();
    ois.close();
    System.out.println(newUser.getUsername());     
    index++;
    }

 }

but I am getting error on running


Exception in thread "main" java.io.InvalidClassException: oodj.User; local class incompatible: stream classdesc serialVersionUID = -7994693857260427394, local class serialVersionUID = 4996613179002222501

any ideas? Thank you

Jens
  • 67,715
  • 15
  • 98
  • 113
  • What line does the error occur? – Eamonn McEvoy Jul 30 '14 at 08:45
  • possible duplicate of [Java serialization - java.io.InvalidClassException local class incompatible](http://stackoverflow.com/questions/8335813/java-serialization-java-io-invalidclassexception-local-class-incompatible) – izstas Jul 30 '14 at 08:48
  • 1
    Looks like the class wich is stored in file is not the same as your `User` class. Are you sure that the class in dat file is a user object? – Jens Jul 30 '14 at 08:49
  • jens, yes it is the same. actually now I am getting what I want but still error exists after result this is output: Shaher Sam Monir Omar Phaisal Exception in thread "main" java.io.InvalidClassException: oodj.User; local class incompatible: stream classdesc serialVersionUID = 4996613179002222501, local class serialVersionUID = -7994693857260427394 at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371) at oodj.test.viewEngingeer(test.java:31) at oodj.OODJ.main(OODJ.java:14) Java Result: 1 – Shaher Jamal Eddin Jul 30 '14 at 09:00
  • Dmitry Tsechoev Thank you worked after I removed all old files and created new ones after adding static final long serialVersionUID = 42L; – Shaher Jamal Eddin Jul 30 '14 at 09:12

1 Answers1

1

Deserialization is impossible. Java can not restore object. You need add something like this:

 static final long serialVersionUID = 42L; 

in your class User and make User implements Serializable.

See more here: Serializabe

DmitryKanunnikoff
  • 2,226
  • 2
  • 22
  • 35