Atom Blog

Como Crear Archivos en Java usando Netbeans 7.1


En este ejemplo se mostrara como crear un archivo para escribir datos almacenados en el programa y como leerlos al iniciar el mismo.

Para ello se hace uso de las clases ObjectInputStream y ObjectOutputStream para poder escribir y leer el archivo creado.

A continuación se mostrara un ejemplo sencillo que como hacer esto.

public class archivoJava() implements Serializable {
     public Persona personas[]; //vector es es de tipo serializable Persona que tiene los atributos
     private ObjectInputStream input; //objeto para leer el archivo
     private ObjectOutputStream output; //objeto para poder escribir en el archivo

     public archivoJava(Persona[] personas) {
          this.personas = personas;
     } //Fin del constructor
  
     //Método que permite guardar un archivo de texto
     public void guardarArchivo() {
          try {
              output = new ObjectOutputStream(new FileOutputStream("archivo.txt"));
              output.writeObject(getPersonas());
              output.close();
          }catch (Exception e) {
              JOptionPane.showMessageDialog(null, "Error al guardar archivo", "Mensaje",
              JOptionPane.WARNING_MESSAGE);                                                                                                 
         }
     } //Fin del método guardarArchivo

     //Método que permite leer un archivo de texto
     public void leerArchivo() {
      try{
            input=new ObjectInputStream(new FileInputStream("archivo.txt"));
            personas=(Persona[])input.readObject(); //personas es una clase serializable
            setnPersona(numPersonas());
            input.close();
      }catch (IOException e) {}
        catch (ClassNotFoundException e) {}
    }  //Fin del método leerArchivo   

} //Fin de la clase








2 comentarios:

  1. SAludos. a ver si me pueden ayudar por favor.

    Guardo los datos de los pacientes: numero de expediente, dni, apellidos, nombres, telefono, direccion y fotografia en un archivo binario, pero al parecer se sobreescribe el archivo, por eso cuando busco solo me muestra el ultimo ingresado, dejo aqui los codigos de guardar y buscar respectivament para que me puedan ayudar. gracias:

    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){}
    }

    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();
    Object dni = filein.readObject();
    Object apellidos = filein.readObject();
    Object nombres = filein.readObject();
    Object direccion = filein.readObject();
    Object telefono = filein.readObject();
    Object foto = filein.readObject();
    if (txtNroExpediente.getText().equals(expediente)){
    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){}
    }

    correo gyaurivictorher@crece.uss.edu.pe vgaraysoft@hotmail.com

    ResponderBorrar
  2. SAludos. a ver si me pueden ayudar por favor.

    Guardo los datos de los pacientes: numero de expediente, dni, apellidos, nombres, telefono, direccion y fotografia en un archivo binario, pero al parecer se sobreescribe el archivo, por eso cuando busco solo me muestra el ultimo ingresado, dejo aqui los codigos de guardar y buscar respectivament para que me puedan ayudar. gracias:

    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){}
    }

    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();
    Object dni = filein.readObject();
    Object apellidos = filein.readObject();
    Object nombres = filein.readObject();
    Object direccion = filein.readObject();
    Object telefono = filein.readObject();
    Object foto = filein.readObject();
    if (txtNroExpediente.getText().equals(expediente)){
    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){}
    }

    correo gyaurivictorher@crece.uss.edu.pe vgaraysoft@hotmail.com

    ResponderBorrar