Mostrando entradas con la etiqueta Serializable. Mostrar todas las entradas
Mostrando entradas con la etiqueta Serializable. Mostrar todas las entradas

lunes, 18 de marzo de 2013

Desde un Archivo Binario de objetos obtener un Archivo de Texto

Desde un archivo Binario de objetos obtener un archivo de texto con el siguiente formato: nombre\n edad\n sexo\n y exhibir el archivo de texto.
import java.io.ObjectInputStream;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.EOFException;
import java.io.Serializable;

class Persona implements Serializable
{
 String nomb;
 int ed;
 char sexo;
}

public class Bin_Text {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        
        ObjectInputStream lee=null;
        
        String nomb="";
        int ed=0;
        char sexo =0;
        
        try
        {
         lee=new ObjectInputStream(new BufferedInputStream(new FileInputStream("persona.bin")));
         FileOutputStream e = new FileOutputStream("NuevoArchivo.txt");
         DataOutputStream escribe = new DataOutputStream(e);

         for (int i=0;i < 5 ; i++)
         {
             nomb=lee.readUTF();
             ed=lee.readInt();
             sexo=lee.readChar();
             
             escribe.writeUTF(nomb);
             escribe.writeInt(ed);
             escribe.writeChar(sexo);
             
         }escribe.close();
        }
        finally
        {
            System.out.println("Archivo creado...");
            lee.close();
        }
        
        System.out.println("Leyendo archivo creado...");
        System.out.println("\n   Nombre\t\tEdad\tSexo");
        DataInputStream lee2 =null;
        try
        {
            lee2 =new DataInputStream(new BufferedInputStream(new FileInputStream("NuevoArchivo.txt")));
            while(true)
            {
                nomb=lee2.readUTF();
                ed=lee2.readInt();
                sexo=lee2.readChar();
                System.out.printf("%s\t%d\t%c\n",nomb,ed,sexo);
            }
        }
        catch (EOFException e)
        {
            System.out.println("\nSe alcanzo el fin del archivo...");
        }
        finally
        {
            lee2.close();
        }
    }
}
Output:
Archivo creado...
Leyendo archivo creado...

     Nombre                      Edad Sexo
0  Jose Manuel Sanchez  23    M
1  Jose Manuel Sanchez 23  M
2  Jose Manuel Sanchez 23  M
3  Jose Manuel Sanchez 23  M
4  Jose Manuel Sanchez 23  M

Se alcanzo el fin del archivo...

Entradas populares