elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Sigue las noticias más importantes de seguridad informática en el Twitter! de elhacker.NET


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  guardar y leer objetos en archivos binarios
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: guardar y leer objetos en archivos binarios  (Leído 3,679 veces)
victor garay

Desconectado Desconectado

Mensajes: 1


Ver Perfil
guardar y leer objetos en archivos binarios
« 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.


En línea

Usuario Invitado


Desconectado Desconectado

Mensajes: 625



Ver Perfil
Re: guardar y leer objetos en archivos binarios
« Respuesta #1 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
  1. private void btcGuardarActionPerformed(java.awt.event.ActionEvent evt) {                                          
  2. String nombreArchivo = archivo;
  3. try{
  4. ObjectOutputStream fileout = new ObjectOutputStream(new FileOutputStream(nombreArchivo));
  5. fileout.writeObject(expediente);
  6. JOptionPane.showMessageDialog(null, "Los datos del paciente se guardaron corecttamente...");
  7. }catch(IOException e){}
  8. desactivarTextFields();
  9. btcGuardar.setEnabled(false);
  10. btcNuevo.setEnabled(true);
  11. btcBuscar.setEnabled(false);
  12. }

Código
  1. private void btcBuscarActionPerformed(java.awt.event.ActionEvent evt) {                                    
  2.        String nombreArchivo = archivo;
  3.        try{
  4.            try (ObjectInputStream filein = new ObjectInputStream(new FileInputStream((String) nombreArchivo))){
  5.                Expediente expediente = null;
  6.            while((expediente = filein.readObject() != null) {
  7. if (txtNroExpediente.getText().equals(expediente.getText())){
  8. String nroExpediente = expediente.getNroExpediente();
  9. String dni = expediente.getDni();
  10. String apellidos = expediente.getApellidos();
  11. String nombres = expediente.getNombres();
  12. String direccion = expediente.getDireccion();
  13. String telefono = expediente.getTelefono();
  14. Icon foto = (Icon) expediente.getFoto();
  15. txtNroExpediente.setText(nroExpediente);
  16. txtDni.setText(dni);
  17. txtApellidos.setText(apellidos);
  18. txtNombres.setText(nombres);
  19. txtDireccion.setText(direccion);
  20. txtTelefono.setText(telefono);
  21. lblFoto.setIcon(foto);
  22. }
  23.            } catch (ClassNotFoundException ex) {
  24.                Logger.getLogger(JDPacientes.class.getName()).log(Level.SEVERE, null, ex);
  25.            }
  26.        }catch(IOException e){}  
  27.    }
  28. }


Saludos.


En línea

"La vida es muy peligrosa. No por las personas que hacen el mal, si no por las que se sientan a ver lo que pasa." Albert Einstein
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Leer datos binarios del registro
Programación Visual Basic
Kizar 6 4,104 Último mensaje 17 Julio 2006, 23:31 pm
por Kizar
Leer Datos Binarios
Programación Visual Basic
David Vans 8 2,517 Último mensaje 11 Abril 2007, 16:36 pm
por ~~
Guardar Objetos
.NET (C#, VB.NET, ASP)
David Vans 2 2,401 Último mensaje 30 Mayo 2007, 15:05 pm
por »~^~«CkNU!»~^~«
[Solucionado] Error al guardar datos binarios
Programación Visual Basic
Sancho.Mazorka 3 2,644 Último mensaje 26 Octubre 2010, 04:12 am
por Sancho.Mazorka
[AYUDA][PYTHON] Leer y guardar archivos .exe de forma hexadecimal en python???
Scripting
Noxware 3 5,367 Último mensaje 22 Agosto 2014, 09:33 am
por Eleкtro
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines