-
-
Save lucasDRR/5e501677a6930b4df33b4fcac7f81048 to your computer and use it in GitHub Desktop.
Java: Lectura y Escritura de Objetos en archivos
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.Serializable; | |
public class Articulos implements Serializable { | |
/** | |
* Los campos que sean necesarios | |
*/ | |
private static final long serialVersionUID = 1L; | |
private int codigo; | |
private double precio; | |
private String nombre; | |
public Articulos() { | |
} | |
public Articulos(int codigo, double precio, String nombre) { | |
super(); | |
this.codigo = codigo; | |
this.precio = precio; | |
this.nombre = nombre; | |
} | |
public int getCodigo() { | |
return codigo; | |
} | |
public double getPrecio() { | |
return precio; | |
} | |
public String getNombre() { | |
return nombre; | |
} | |
public void setPrecio(double precio) { | |
this.precio = precio; | |
} | |
@Override | |
public String toString() { | |
return "articulo: " + codigo + " " + nombre + " " + " $ " + precio; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileNotFoundException; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.ObjectInputStream; | |
import java.io.ObjectOutputStream; | |
import java.io.StreamCorruptedException; | |
import java.util.ArrayList; | |
public class ArticulosAArchivo { | |
public static void guardarElementosDeLista(ArrayList<Articulos> lista) { | |
FileOutputStream fos = null; | |
ObjectOutputStream oos = null; | |
File archivo = new File("elementos.bat"); | |
try { | |
/* Se mantiene el archivo con los ultimos datos escritos | |
* | |
* Siempre leer los datos al iniciar el programa para evitar perdidas, | |
* los cambios se deben realizan primero en la lista y luego se guardan en el archivo | |
* | |
* Si tenes 2 listas y las queres guardar separadas envia una lista de listas aunque | |
* es mejor guardarlas en dos archivos separados | |
* | |
* si ya guardaste una lista A y queres agregar a esa lista los elementos de una | |
* lista B entonces Recupera A -> Agrega los elementos de B a A-> guarda A | |
* | |
* Si no queres borrar los elemetos de la lista tenes que | |
* crear una clase que extienda a ObjectInputStream: | |
* sobre-escribir el método writeStreamHeader(){} para que no haga nada como | |
* explica en el enlace que te envie antes. | |
* ( si tu programa va a guardar muchos articulos es conveniente hacerlo de esta manera) | |
* | |
* */ | |
if( archivo.exists() ) archivo.delete(); // elimina el anterior antes de escribir el nuevo | |
fos = new FileOutputStream("elementos.bat", true); | |
oos = new ObjectOutputStream(fos); | |
for(Articulos a : lista) { // guarda los elementos de la lista | |
oos.writeObject(a); | |
} | |
System.out.println("lista guardada ... "); | |
} catch (FileNotFoundException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
}catch( IOException e) { | |
e.printStackTrace(); | |
}finally { | |
if( oos != null) { | |
try { | |
oos.close(); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
if( fos != null) { | |
try { | |
fos.close(); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
public static ArrayList<Articulos> ObtenerElementosDeLista() { | |
FileInputStream fis = null; | |
ObjectInputStream ois = null; | |
ArrayList<Articulos> lista = new ArrayList<>(); | |
try { | |
fis = new FileInputStream("elementos.bat"); | |
ois = new ObjectInputStream(fis); | |
Articulos art; | |
// Recuperar los elementos y guardarlos en una lista | |
while(fis.available() != 0) { | |
art = (Articulos) ois.readObject(); | |
if(art != null) lista.add(art); | |
} | |
} catch (FileNotFoundException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
}catch(ClassNotFoundException e){ | |
e.printStackTrace(); | |
} | |
catch( IOException e) { | |
e.printStackTrace(); | |
}finally { | |
if( ois != null) { | |
try { | |
ois.close(); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
if( fis != null) { | |
try { | |
fis.close(); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
} | |
return lista; | |
} | |
public static void guardarLista(ArrayList<Articulos> lista) { | |
FileOutputStream fos = null; | |
ObjectOutputStream oos = null; | |
try { | |
fos = new FileOutputStream("archivo.bat"); | |
oos = new ObjectOutputStream(fos); | |
oos.writeObject(lista); | |
} catch (FileNotFoundException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
}catch( IOException e) { | |
e.printStackTrace(); | |
}finally { | |
if( oos != null) { | |
try { | |
oos.close(); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
if( fos != null) { | |
try { | |
fos.close(); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
} | |
System.out.println("✅ ... lista guardada"); | |
} | |
public static ArrayList<Articulos> recuperarLista(){ | |
ArrayList<Articulos> lista = null; | |
try( var ois = new ObjectInputStream( new FileInputStream("archivo.bat"))){ // sintaxis mas nueva moderna | |
lista = (ArrayList<Articulos>) ois.readObject(); // advertencia el compilador no sabe lo que biene desde object | |
}catch(StreamCorruptedException e) { | |
e.printStackTrace(); | |
}catch(IOException e) { | |
e.printStackTrace(); | |
}catch(ClassNotFoundException e) { | |
e.printStackTrace(); | |
} | |
return lista; | |
} | |
public static void verLista(ArrayList<Articulos> lista) { | |
if(lista.size() == 0) { | |
System.out.println("⛔ ... a lista no tiene elementos "); | |
}else { | |
for(Articulos a : lista) { | |
System.out.println(a); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
public class Entrada { | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
ArrayList<Articulos> listaArticulos = new ArrayList<Articulos>(); | |
listaArticulos.add( new Articulos(101, 15.50, "Pan")); | |
listaArticulos.add( new Articulos(102, 20.00, "Huevos")); | |
listaArticulos.add( new Articulos(103, 16.75, "Sal")); | |
listaArticulos.add( new Articulos(104, 10.25, "Leche")); | |
System.out.println("Lista Original"); | |
ArticulosAArchivo.verLista(listaArticulos); | |
ArticulosAArchivo.guardarLista(listaArticulos); | |
listaArticulos.clear(); | |
System.out.println("Limpiando lista: "); | |
ArticulosAArchivo.verLista(listaArticulos); | |
listaArticulos = ArticulosAArchivo.recuperarLista(); | |
System.out.println("Lista recuperada: "); | |
ArticulosAArchivo.verLista(listaArticulos); | |
// agregar articulos a la lista | |
listaArticulos.add(new Articulos(105, 12.79, "Manteca")); | |
listaArticulos.add(new Articulos(106, 20.75, "Azucar")); | |
listaArticulos.add(new Articulos(107, 12.79, "Chocolate")); | |
listaArticulos.add(new Articulos(108, 12.79, "Arroz")); | |
// cambiar el precio de la leche ( mejorable ) | |
Articulos art; | |
for(int i = 0 ; i < listaArticulos.size(); i++) { | |
if(listaArticulos.get(i).getNombre().equals("Leche") ) { | |
art = listaArticulos.get(3); | |
art.setPrecio(19.99); | |
listaArticulos.set(3, art); | |
break; | |
} | |
} | |
// Guardar la lista (sobre-escribe la anterior) | |
ArticulosAArchivo.guardarLista(listaArticulos); | |
//Limpiar la lista ( solo para pruebas ) | |
listaArticulos.clear(); | |
System.out.println("Limpiando lista: "); | |
ArticulosAArchivo.verLista(listaArticulos); | |
// recuperar nuevamente la lista | |
listaArticulos = ArticulosAArchivo.recuperarLista(); | |
System.out.println("Lista recuperada: "); | |
ArticulosAArchivo.verLista(listaArticulos); | |
/* | |
* PRUEBAS CON ELEMENTOS | |
* */ | |
// guardar elementos (la lista debe estar llena) | |
ArticulosAArchivo.guardarElementosDeLista(listaArticulos); | |
System.out.println("Mostrar lista reconstruida desde elementos del archivo: "); | |
// Recuperar elementos | |
listaArticulos = ArticulosAArchivo.ObtenerElementosDeLista(); | |
//mostrar los articulos | |
if(listaArticulos != null) { | |
for(Articulos a : listaArticulos) { | |
System.out.println(a); | |
} | |
} | |
listaArticulos.add(new Articulos(109, 12.00, "Agua")); | |
listaArticulos.add(new Articulos(110, 23.67, "Fideos")); | |
// guardar elementos 2da vez (la lista debe estar llena) | |
ArticulosAArchivo.guardarElementosDeLista(listaArticulos); | |
System.out.println("Mostrar lista reconstruida desde elementos del archivo: "); | |
// Recuperar elementos 2da vez | |
listaArticulos = ArticulosAArchivo.ObtenerElementosDeLista(); | |
//mostrar los articulos 2 vez | |
if(listaArticulos != null) { | |
for(Articulos a : listaArticulos) { | |
System.out.println(a); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sos un tipaso lucas te agradezco un monton. Mi profesor no nos explico nada en todo el cuatrimestre y nos mandó a hacer un programa super complejo (para mi) para el final. Estoy buscando por mi cuenta aprender hace varias semanas ya jajaja, muchas gracias!!