Ransford Anderson
Ransford Anderson

Reputation: 39

local class incompatible error

The following code gives me the error InvalidClassException My User class implements Serializable so I'm lost. I'm trying to store list filled with User objects and then be able to read it back.

List<User> userList = new ArrayList<User>();//list used
try {
    ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(fileName, true));

    os.writeObject(userList);
    os.close();
} catch (IOException e1) {
    e1.printStackTrace();
}

// input
try {
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
    userList = (List<User>) ois.readObject();
    ois.close();
} catch (FileNotFoundException e1) {
    e1.printStackTrace();
} catch (IOException e1) {
    e1.printStackTrace();
} catch (ClassNotFoundException e1) {
    e1.printStackTrace();
}

Upvotes: 2

Views: 94

Answers (1)

AJNeufeld
AJNeufeld

Reputation: 8695

If you are trying to store and later retrieve a single object (a List<> in your example) in a file, you do not want to append to the file each time you write to it. Rather, you want to overwrite the file each time, with the new object.

// Write
List<User> userList = new ArrayList<User>();
try (FileOutputStream fos = new FileOutputStream(fileName);
        ObjectOutputStream oos = new ObjectOutputStream(fos)) {
    oos.writeObject(userList);
} catch (IOException e1) {
    e1.printStackTrace();
}

// read
try (FileInputStream fis = new FileInputStream(fileName);
        ObjectInputStream ois = new ObjectInputStream(fis)) {
    userList = (List<User>) ois.readObject();
} catch (FileNotFoundException  | IOException | ClassNotFoundException e1) {
    e1.printStackTrace();
}

Notice new FileOutputStream(fileName) does not have the true argument. Using the true argument indicates you want to open the file for "append". Using false, or leaving the append argument off entirely, will open the file for "overwrite".

Notes:

I've also used the try-with-resources statement my example. This eliminates the need for explicitly closing the streams; the streams are automatically closed for you at the end of the try { } block.

I've also used the multi-catch clause, because you are not handling the 3 exceptions any differently, so it is a bit cleaner.

Upvotes: 1

Related Questions