Сериализация Java / десериализация ArrayList работает только при первом выполнении программы - PullRequest
0 голосов
/ 03 ноября 2018

Я пытаюсь сериализовать и десериализовать ArrayList с некоторыми объектами. В первый раз, когда я запускаю программу, все работает, но в следующий раз она не работает:

public class Test {

    private static final String FILE_NAME = "Objects.ser";

    public static void main(String[] args) {

        ArrayList<CustomObject> customObjects = getCustomObjects();
        System.out.println("CustomObjects count: "+customObjects.size());
        System.out.println("Adding 5 CustomObjects");
        Random rand = new Random();
        for(int i=0; i<5; i++){
            CustomObject obj = new CustomObject();
            obj.setIntValue(rand.nextInt());
            customObjects.add(obj);
        }
        System.out.println("CustomObjects count: "+customObjects.size());
        System.out.println("Save and load CustomObjects");
        saveCustomObjects(customObjects);
        customObjects = getCustomObjects();
        System.out.println("CustomObjects count: "+customObjects.size());
    }

    public static ArrayList<CustomObject> getCustomObjects(){
        try (
            FileInputStream fin = new FileInputStream(FILE_NAME);
            ObjectInputStream ois = new ObjectInputStream(fin);
        ){
            return (ArrayList<CustomObject>) ois.readObject();

        } catch (Exception ex) {
            return new ArrayList<>();
        }

    }

    public static void saveCustomObjects(ArrayList<CustomObject> strategies) {
        try(
            FileOutputStream fout = new FileOutputStream(FILE_NAME, true);
            ObjectOutputStream oos = new ObjectOutputStream(fout);
        ){
            oos.writeObject(strategies);
            //tried also with oos.flush();

        } catch (Exception ex) {

            ex.printStackTrace();
        }
    }
}
public class CustomObject implements Serializable{

    static final long serialVersionUID = 42L;

    private int intValue=0;
    private EnumTypes enumType=EnumTypes.ENUM_TYPE_ONE;

    public enum EnumTypes{
        ENUM_TYPE_ONE, ENUM_TYPE_TWO
    }

    public int getIntValue() {
        return intValue;
    }

    public void setIntValue(int intValue) {
        this.intValue = intValue;
    }

    public EnumTypes getEnumTypes() {
        return enumType;
    }

    public void setEnumTypes(EnumTypes enumTypes) {
        this.enumType = enumTypes;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 97 * hash + this.intValue;
        hash = 97 * hash + Objects.hashCode(this.enumType);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final CustomObject other = (CustomObject) obj;
        if (this.intValue != other.intValue) {
            return false;
        }
        if (this.enumType != other.enumType) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "CustomObject{" + "intValue=" + intValue + ", enumTypes=" + enumType + '}';
    }
}

Выходные данные первого запуска приложения показывают все, как ожидалось:

CustomObjects count: 0
Adding 5 CustomObjects
CustomObjects count: 5
Save and load CustomObjects
CustomObjects count: 5

Но после следующих запусков выходные данные всегда выглядят так, как будто файл с объектами в сериализованном ArrayList не может быть перезаписан:

CustomObjects count: 5
Adding 5 CustomObjects
CustomObjects count: 10
Save and load CustomObjects
CustomObjects count: 5

Я тестировал в NetBeans и консоли на Mac. Кто-нибудь знает в чем проблема?

1 Ответ

0 голосов
/ 03 ноября 2018

Это именно то, что ничего не перезаписывается, поскольку вы явно добавили, а не перезаписали при записи в файл:

new FileOutputStream(FILE_NAME, true); 

Таким образом, первый запуск ничего не читает и добавляет список из 5 элементов в файл. Второй прогон считывает уникальный список и добавляет в файл еще один список из 10 элементов. Третий прогон считывает первый список в файле и добавляет еще один список из 10 элементов и т. Д.

Удалить второй аргумент или установить его в false.

...