I need to store objects in files (.txt, .mio, .Whatever)
I'm using java
I have tried to implement the Serialize class to serialize objects and then store them, but I could not get the desired result.
EDIT
The idea is to store multiple objects in the same file and then open the file and look for a specific object, manipulate objects. etc. it is as if it were a SQL database only with objects stored in files.
which would be a solution to this? a way of storing objects in files and then you can call them, search for them, store them in an array.
Would appreciate any idea and help.
CODE
import java.io.Serializable;
public class Contacto implements Serializable {
private String nombre;
private String apellido;
public Contacto(String nombre, String apellido){
this.nombre = nombre;
this.apellido = apellido;
}
public String getNombre(){
return this.nombre;
}
public String getApellido(){
return this.apellido;
}
public void setNombre(String n){
this.nombre = n;
}
public void setApellido(String a){
this.apellido = a;
}
public String toString(){
return this.getApellido() +" "+ this.getNombre();
}
}
////////////////////////////////////////////////////////////////////////////
import java.io.*;
public class Serializador{
// Escribe un objecto en un archivo
private ObjectOutputStream escritorArchivo;
// Lee un objecto que este guardado en un archivo
private ObjectInputStream lectorArchivo;
// Al metodo le pasamos el objeto que queremos serializar y lo guardará en el archivo que se le especifique al FileOutputStream (en este caso "objeto.mio")
public void escribirArchivo(Object objeto){
try{
escritorArchivo = new ObjectOutputStream(new FileOutputStream("objeto.mio"));
escritorArchivo.writeObject(objeto);
} catch(FileNotFoundException fnfex){
fnfex.printStackTrace();
} catch(IOException ioex){
ioex.printStackTrace();
}
}
public Object leerArchivo(String rutaArchivo){
Object lectura = null;
try{
lectorArchivo = new ObjectInputStream(new FileInputStream(rutaArchivo));
lectura = lectorArchivo.readObject();
} catch(FileNotFoundException fnfex){
fnfex.printStackTrace();
} catch(IOException ioex){
ioex.printStackTrace();
} catch(ClassNotFoundException cnfex){
cnfex.printStackTrace();
}
return lectura;
}
}
the code shows how the basic idea, however it is an idea that can be discarded.
Thank you very much.