Last active
September 27, 2024 06:40
-
-
Save corlaez/438d0d2fa4574f48f96012fd4a004645 to your computer and use it in GitHub Desktop.
Codigo para persistir objetos en Java
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
package clases; | |
import java.io.Serializable; | |
public class Cliente implements Serializable { | |
private static final long serialVersionUID = 1_000_000_000_000_001L; | |
private Integer codigo; | |
private String nombre; | |
private String apellido; | |
private int dni; | |
private int telefono; | |
// Constructor que inicializa los atributos | |
public Cliente(String nombre, String apellido, int dni, int telefono) { | |
this.codigo = null; | |
this.nombre = nombre; | |
this.apellido = apellido; | |
this.dni = dni; | |
this.telefono = telefono; | |
} | |
// Métodos getters y setters para acceder y modificar los atributos | |
public int getCodigo() { | |
return codigo; | |
} | |
public void setCodigo(Integer codigo) { | |
this.codigo = codigo; | |
} | |
public String getNombre() { | |
return nombre; | |
} | |
public void setNombre(String nombre) { | |
this.nombre = nombre; | |
} | |
public String getApellido() { | |
return apellido; | |
} | |
public void setApellido(String apellido) { | |
this.apellido = apellido; | |
} | |
public int getDni() { | |
return dni; | |
} | |
public void setDni(int dni) { | |
this.dni = dni; | |
} | |
public long getTelefono() { | |
return telefono; | |
} | |
public void setTelefono(int telefono) { | |
this.telefono = telefono; | |
} | |
// Método toString para mostrar la información del cliente | |
@Override | |
public String toString() { | |
return "Cliente{" + "codigo=" + codigo + ", nombre='" + nombre + '\'' + ", apellido='" + apellido + '\'' | |
+ ", dni=" + dni + ", telefono=" + telefono + '}'; | |
} | |
} |
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
package arreglos; | |
import java.util.ArrayList; | |
import clases.Cliente; | |
public class Clientes { | |
private ArrayList<Cliente> clientes; | |
@Override | |
public String toString() { | |
return "Clientes [clientes=" + clientes + "]"; | |
} | |
// Constructor | |
public Clientes() { | |
clientes = new ArrayList<>(); | |
} | |
public void llenarConDataDePrueba() { | |
adicionar(new Cliente("Carmen", "Sanchez", 45874558, 965898985)); | |
adicionar(new Cliente("Juan", "Perez", 40987654, 987654321)); | |
adicionar(new Cliente("Maria", "Gomez", 35678912, 934567890)); | |
adicionar(new Cliente("Rita", "Grau", 35678912, 934567890)); | |
adicionar(new Cliente("Pedro", "Tenorio", 35678912, 934567890)); | |
} | |
public void adicionar(Cliente cliente) { | |
if (clientes.isEmpty()) | |
cliente.setCodigo(1); | |
else { | |
Integer newCodigo = clientes.get(clientes.size() - 1).getCodigo() + 1; | |
cliente.setCodigo(newCodigo); | |
} | |
clientes.add(cliente); | |
} | |
public Cliente obtener(int indice) { | |
return clientes.get(indice); | |
} | |
public Cliente buscarPorCodigo(int codigo) { | |
for (Cliente cliente : clientes) { | |
if (cliente.getCodigo() == codigo) { | |
return cliente; | |
} | |
} | |
return null; | |
} | |
public void limpiar() { | |
clientes.clear(); | |
} | |
public void eliminar(Cliente cliente) { | |
Cliente clienteEnListado = buscarPorCodigo(cliente.getCodigo()); | |
clientes.remove(clienteEnListado); | |
} | |
public void cargarDatos() { | |
clientes = common.IoUtils.leerClientesDeArchivo(); | |
System.out.println(clientes); | |
} | |
public void guardarDatos() { | |
common.IoUtils.salvarClientesAlArchivo(clientes); | |
} | |
} |
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.* | |
import java.nio.file.Files | |
private const val directory = "datos" | |
fun <T> readObjectFromFile(fileName: String): T { | |
return try { | |
ObjectInputStream(FileInputStream("$directory/$fileName").buffered()).use { | |
@Suppress("UNCHECKED_CAST") | |
it.readObject() as T | |
} | |
} catch (e: Exception) { | |
throw RuntimeException("Problema al leer el archivo $directory/$fileName", e) | |
} | |
} | |
fun writeObjectToFile(content: Any, fileName: String) { | |
val file = File("$directory/$fileName") | |
ensureFileExists(file) | |
try { | |
ObjectOutputStream((FileOutputStream(file).buffered())).use { oos -> | |
oos.writeObject(content) | |
} | |
} catch (e: NotSerializableException) { | |
throw RuntimeException("El objeto content requiere ser anotado con @Serializable", e) | |
} catch (e: Exception) { | |
throw RuntimeException("Problema al salvar el archivo $directory/$fileName", e) | |
} | |
} | |
fun ensureFileExists(file: File) { | |
val datosDir = File(directory) | |
if(!datosDir.exists()) Files.createDirectory(datosDir.toPath()) | |
if(!file.exists()) Files.createFile(file.toPath()) | |
} |
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
package common; | |
import java.io.*; | |
import java.util.ArrayList; | |
import arreglos.Clientes; | |
import clases.*; | |
public class IoUtils { | |
private static String FILENAME_BOLETAS = "Boletas"; | |
private static String FILENAME_CLIENTES = "Clientes"; | |
private static String FILENAME_PRODUCTOS = "Productos"; | |
public static void main(String[] args) { | |
Clientes clientes = new Clientes(); | |
clientes.cargarDatos(); | |
clientes.limpiar(); | |
clientes.llenarConDataDePrueba(); | |
clientes.guardarDatos(); | |
} | |
public static void salvarBoletasAlArchivo(ArrayList<Boleta> boletas) { | |
salvarObject(boletas, FILENAME_BOLETAS); | |
} | |
public static void salvarClientesAlArchivo(ArrayList<Cliente> clientes) { | |
salvarObject(clientes, FILENAME_CLIENTES); | |
} | |
public static void salvarProductosAlArchivo(ArrayList<Producto> productos) { | |
salvarObject(productos, FILENAME_PRODUCTOS); | |
} | |
@SuppressWarnings("unchecked") | |
public static ArrayList<Boleta> leerBoletasDeArchivo() { | |
return (ArrayList<Boleta>) leerObjetoDeArchivo(FILENAME_BOLETAS); | |
} | |
@SuppressWarnings("unchecked") | |
public static ArrayList<Cliente> leerClientesDeArchivo() { | |
return (ArrayList<Cliente>) leerObjetoDeArchivo(FILENAME_CLIENTES); | |
} | |
@SuppressWarnings("unchecked") | |
public static ArrayList<Producto> leerProductosDeArchivo() { | |
return (ArrayList<Producto>) leerObjetoDeArchivo(FILENAME_PRODUCTOS); | |
} | |
private static Object leerObjetoDeArchivo(String fileName) { | |
File file = new File(fileName); | |
try(FileInputStream fis = new FileInputStream(file); | |
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(fis)); | |
) { | |
return ois.readObject(); | |
} catch (Exception e) { | |
throw new RuntimeException("Problema al leer el archivo " + fileName); | |
} | |
} | |
private static void salvarObject(Object content, String fileName) { | |
File file = new File("datos/" + fileName); | |
try(FileOutputStream fos = new FileOutputStream(file); | |
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(fos))){ | |
oos.writeObject(content); | |
oos.flush(); | |
} catch (Exception e) { | |
throw new RuntimeException("Problema al salvar el archivo " + fileName); | |
} | |
} | |
// en desuso actualmente pero podriamos usarlo si es que decidimos serializar aparte de otro modo | |
private static void salvarString(String content, String fileName) { | |
try { | |
FileWriter fileWriter = new FileWriter("datos/" + fileName); | |
BufferedWriter output = new BufferedWriter(fileWriter); | |
output.write(content); | |
output.flush(); | |
output.close(); | |
} catch (Exception e) { | |
throw new RuntimeException("Problema al salvar el archivo " + fileName); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment