Work with a serialized object extracted from a file.ser in Java

0

Good afternoon.

I am a beginner in Java and I am working right now with the storage of objects in serialized files using the methods of class Object ( ObjectInput and ObjectOutput ).

When I save the object I do not have problems, but when I try to add it to the program, I do not have much idea of how to do it, in terms of declaration and initialization of that same object extracted from the serialized file.

This is my code to load the object

    private File player= new File("./data/players.ser");

    public void loadPlayer(){
        try {
            ObjectInput input = new ObjectInputStream(new FileInputStream(player));
            //Procedimiento para realizar el input.readObject(); ???
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    
asked by JD0001 07.02.2017 в 19:57
source

1 answer

0
private File player= new File("./data/players.ser");

public void loadPlayer(){
    try {
        ObjectInput input = new ObjectInputStream(new FileInputStream(player));
        //Procedimiento para realizar el input.readObject(); ???

        TuClase objetoSerializable = (TuClase)input.readObject();//Realizas el casting hacia el objeto de tu clase
        input.close();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

Do not forget that the files generated with TuClase, will not fit in Cast (Casting is called to the assignment of compatible objects of different type) if you modify the class -you would have to generate files again- unless you define the serialVersionUID -as he points out in the attached page Chuidiang- being very possible you need to modify when you are developing

Chiudiang: Serialization of objects in java

Class ObjectInputStream

    
answered by 07.02.2017 / 20:18
source