Fill table with the data of a serialized file

1

I have this code that serializes a class to me Contact:

@Override
public void serializar() {
       Contacto a= new Contacto();
    try {
        FileOutputStream fos= new FileOutputStream("contactos.dat");
        ObjectOutputStream oos= new ObjectOutputStream(fos);

        if(oos != null)
        {
            oos.writeObject(a);
            oos.close();
            JOptionPane.showMessageDialog(null, "Contacto guardado");
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Hubo un error en el proceso\n"
                + "Ha ocurrido el siguiente error: \n"+e);
    }
}

and this one that deserializa the file:

  public void deserializar() {
    Contacto a;

    try {
        File file=new File("contactos.dat");

        if(file.exists()) {

        FileInputStream fis= new FileInputStream(file);
        ObjectInputStream ios= new ObjectInputStream(fis);

        if(ios != null){
            a= (Contacto) ios.readObject();
            ios.close();
        }
        }

    } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Hubo un error en el proceso\n"
                + "Ha ocurrido el siguiente error: \n"+e);
    }
}

They are in different classes hence they refer to the class contact in each of them

What I want to know is how I can fill a table with the data generated by the serializer class in the file

    
asked by David Calderon 12.06.2016 в 17:31
source

1 answer

1

It is not necessary to create a serializer / deserializer for each class. You can take generics to use only one.

public class Serializator {

    public static <T> void serialize(String path, T t) {
        try (FileOutputStream fos = new FileOutputStream(path);
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {

             oos.writeObject(t);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> Optional<T> deserialize(String path, Class<T> type) {
        try (FileInputStream fos = new FileInputStream(path);
             ObjectInputStream ios = new ObjectInputStream(fos)) {

             return Optional.of((T) ios.readObject());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace(); // hacer algo en lugar de esto
            return Optional.empty();
        }
    }
}

The usage mode is simple:

Serializator.serialize("/ruta/archivo.dat", objeto);
Optional<Objeto> optObjecto = Serializator.deserialize("/ruta/archivo.dat", Objeto.class);
if(optObjecto.isPresent()) { // si el objeto está presente
    Objeto objeto = optObjeto.get();
    // proceder a insertar
}

Now, I do not understand what you mean by table. Database? JTable / TableView?

Database

    String sql = "INSERT INTO tu_tabla(col1, col2, col3) VALUES(?, ?, ?)";

    try (Connection conn = ConnectionHelper.get();
         PreparedStatement pst = conn.prepareStatement(sql)) {

        pst.setString(1, person.getName());
        pst.setString(2, person.getLastname());
        pst.setDate(3, person.getBirthDate());
        pst.executeUpdate();
    } catch(SQLException e) {
        // hacer algo si falla el insert
    }

Where:

  • ConnectionHelper is a utilitarian class to get the connection

JPA Mode

There is no greater mystery, you get EntityManager and save the object.

entityManager.save(person);

JTable

DefaultTableModel model = (DefaultTableModel) tabla.getModel();
DateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");

model.addRow(new Object[] {
    person.getName(), person.getLastname(), fmt.format(person.getBirthDate())
});
    
answered by 12.06.2016 в 19:23