Test Foro de elhacker.net SMF 2.1

Programación => Programación General => Java => Mensaje iniciado por: victor garay en 17 Abril 2015, 04:57 AM

Título: guardar y leer objetos en archivos binarios
Publicado por: victor garay en 17 Abril 2015, 04:57 AM
Saludos. Guardo los datos de pacientes(n. de expediente, dni, apellidos, nombres, telefono y fotografia) en un archivo binario. el metodo de guardar lo realiza bien, cuando ejecuto la busqueda me muestra solo el ultimo paciente ingresado... aqui les dejo elcodigo del boton guardar y buscar respectivamente:

private void btcGuardarActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        Object nombreArchivo = archivo;
        System.out.println(nombreArchivo);
        try{
            ObjectOutputStream fileout = new ObjectOutputStream(new FileOutputStream((String) nombreArchivo));
            fileout.writeObject(txtNroExpediente.getText());
            fileout.writeObject(txtDni.getText());
            fileout.writeObject(txtApellidos.getText());
            fileout.writeObject(txtNombres.getText());
            fileout.writeObject(txtDireccion.getText());
            fileout.writeObject(txtTelefono.getText());
            fileout.writeObject(lblFoto.getIcon());
            JOptionPane.showMessageDialog(null, "Los datos del paciente se guardaron corecttamente...");
            if(fileout!=null){
                fileout.close();
            }
        }catch(IOException e){}
        desactivarTextFields();
        btcGuardar.setEnabled(false);
        btcNuevo.setEnabled(true);
        btcBuscar.setEnabled(false);
    }

private void btcBuscarActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        Object nombreArchivo = archivo;
        try{
            try (ObjectInputStream filein = new ObjectInputStream(new FileInputStream((String) nombreArchivo))){
                Object expediente = filein.readObject();
            if (txtNroExpediente.getText().equals(expediente)){
                Object dni = filein.readObject();
                Object apellidos = filein.readObject();
                Object nombres = filein.readObject();
                Object direccion = filein.readObject();
                Object telefono = filein.readObject();
                Object foto = filein.readObject();
                txtNroExpediente.setText((String) expediente);
                txtDni.setText((String) dni);
                txtApellidos.setText((String) apellidos);
                txtNombres.setText((String) nombres);
                txtDireccion.setText((String) direccion);
                txtTelefono.setText((String) telefono);
                lblFoto.setIcon((Icon) foto);
            }
                if(filein!=null){
                    filein.close();
                }
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(JDPacientes.class.getName()).log(Level.SEVERE, null, ex);
            }
        }catch(IOException e){}   
    }

de antemano gracias por el apoyo.
Título: Re: guardar y leer objetos en archivos binarios
Publicado por: Usuario Invitado en 17 Abril 2015, 06:51 AM
Hola, Víctor, bienvenido al foro. Te comendo que en el editor tienes las etiquetas GeSHi para colocar código. También veo mucha redundancia en tu código, como declarar nombreArchivo como Object y despues hacer cast a String, en lugar de declararlo String. Otra cosa innecesaria que haces es cerrar los streams cuando estás usando try - catch - resources, ya que ésta estructura cierra los flujos automáticamente, en tu caso de ObjectOutputStream y ObjectInputStream, ya que implementa a la interface AutoCloseable.

Es mucho mejor que crees un POJO que englobe las propiedades del Expediente y guardar éste objeto en el fichero. Si haces ésto, tus métodos quedarían así:

Código (java) [Seleccionar]
private void btcGuardarActionPerformed(java.awt.event.ActionEvent evt) {                                           
String nombreArchivo = archivo;
try{
ObjectOutputStream fileout = new ObjectOutputStream(new FileOutputStream(nombreArchivo));
fileout.writeObject(expediente);
JOptionPane.showMessageDialog(null, "Los datos del paciente se guardaron corecttamente...");
}catch(IOException e){}
desactivarTextFields();
btcGuardar.setEnabled(false);
btcNuevo.setEnabled(true);
btcBuscar.setEnabled(false);
}


Código (java) [Seleccionar]
private void btcBuscarActionPerformed(java.awt.event.ActionEvent evt) {                                   
        String nombreArchivo = archivo;
        try{
            try (ObjectInputStream filein = new ObjectInputStream(new FileInputStream((String) nombreArchivo))){
                Expediente expediente = null;
            while((expediente = filein.readObject() != null) {
if (txtNroExpediente.getText().equals(expediente.getText())){
String nroExpediente = expediente.getNroExpediente();
String dni = expediente.getDni();
String apellidos = expediente.getApellidos();
String nombres = expediente.getNombres();
String direccion = expediente.getDireccion();
String telefono = expediente.getTelefono();
Icon foto = (Icon) expediente.getFoto();
txtNroExpediente.setText(nroExpediente);
txtDni.setText(dni);
txtApellidos.setText(apellidos);
txtNombres.setText(nombres);
txtDireccion.setText(direccion);
txtTelefono.setText(telefono);
lblFoto.setIcon(foto);
}
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(JDPacientes.class.getName()).log(Level.SEVERE, null, ex);
            }
        }catch(IOException e){}   
    }
}



Saludos.