Entrega Actividad 1.8: Tratamiento de ficheros (java.nio) VI - CRUD + DAO + Properties (MapaMundi)
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
# Ignorar la carpeta de compilados
|
||||
bin/
|
||||
*.class
|
||||
|
||||
# Ignorar archivos de configuración de Eclipse
|
||||
.settings/
|
||||
.project
|
||||
.classpath
|
||||
@@ -0,0 +1,3 @@
|
||||
# config/application.properties
|
||||
ruta.fichero.continente=C:\\Users\\lauuj\\aadd\\fic08\\informacion_continentes.csv
|
||||
separador.csv.continente=#
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
/**
|
||||
*
|
||||
*/
|
||||
module Ficheros_03 {
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package org.palomafp.aadd.ljl;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.palomafp.aadd.ljl.dao.IContinenteDAO;
|
||||
import org.palomafp.aadd.ljl.dao.impl.ContinenteDaoFichero;
|
||||
import org.palomafp.aadd.ljl.model.Continente;
|
||||
|
||||
public class GestorMapamundi {
|
||||
|
||||
private IContinenteDAO continenteDao = new ContinenteDaoFichero();
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// lo que nos devuelve el array de los argumentos son Strings, asi que lo parseamos
|
||||
int opcion = Integer.parseInt(args[0]);
|
||||
|
||||
GestorMapamundi gestor = new GestorMapamundi();
|
||||
Continente continente;
|
||||
|
||||
switch(opcion) {
|
||||
|
||||
case 1:
|
||||
// Obtenemos una Lista de continentes
|
||||
List<Continente> continentes = gestor.obtenerListaDeContinentes();
|
||||
|
||||
for (Continente cont : continentes) {
|
||||
System.out.println(cont);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 2:
|
||||
// Obtenemos un Continente por su código
|
||||
continente = gestor.obtenerContinenteDeCodigo(args[1]);
|
||||
System.out.println("El continente que buscas es: " + continente);
|
||||
break;
|
||||
|
||||
case 3:
|
||||
// Insertaremos un continente
|
||||
continente = new Continente(args[1], args[2]);
|
||||
if(gestor.insertarContinente(continente)){
|
||||
System.out.println("Continente insertado correctamente");
|
||||
}else{
|
||||
System.out.println("El continente no se ha podido insertar. Comprueba que el código no exista");
|
||||
};
|
||||
break;
|
||||
|
||||
case 4:
|
||||
// Eliminaremos un continente
|
||||
continente = new Continente(args[1], args[2]);
|
||||
if (gestor.borrarContinente(continente)) {
|
||||
System.out.println("Continente eliminado correctamente");
|
||||
}else{
|
||||
System.out.println("El continente no se ha podido eliminar. Comprueba que el código exista");
|
||||
};
|
||||
break;
|
||||
|
||||
case 5:
|
||||
// Actualizaremos un continente
|
||||
continente = new Continente(args[1], args[2]);
|
||||
if (gestor.actualizarContinente(continente)) {
|
||||
System.out.println("Continente actualizado correctamente");
|
||||
}else{
|
||||
System.out.println("El continente no se ha podido actualizar. Comprueba que el código exista");
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
System.out.println("Opción no esperada");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private boolean actualizarContinente(Continente continente) {
|
||||
|
||||
Continente continenteFichero = continenteDao.obtenerContinentePorCod(continente.getCodigo());
|
||||
if (continenteFichero != null) {
|
||||
return continenteDao.actualizarContinente(continente);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean borrarContinente(Continente continente) {
|
||||
Continente continenteFichero = continenteDao.obtenerContinentePorCod(continente.getCodigo());
|
||||
if (continenteFichero != null) {
|
||||
return continenteDao.eliminarContinente(continente);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean insertarContinente(Continente continente) {
|
||||
|
||||
Continente continenteFichero = continenteDao.obtenerContinentePorCod(continente.getCodigo());
|
||||
if (continenteFichero == null) {
|
||||
return continenteDao.insertarContinenteNuevo(continente);
|
||||
}
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
private Continente obtenerContinenteDeCodigo(String codigoContinente) {
|
||||
Continente continente = continenteDao.obtenerContinentePorCod(codigoContinente);
|
||||
|
||||
return continente;
|
||||
}
|
||||
|
||||
private List<Continente> obtenerListaDeContinentes() {
|
||||
List<Continente> listaContinentes = continenteDao.obtenerListaContinentes();
|
||||
|
||||
return listaContinentes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package org.palomafp.aadd.ljl.config;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Properties;
|
||||
|
||||
public class ConfigManager {
|
||||
|
||||
private static final String RUTA_FICHERO_CONFIGURACION = "config/application.properties";
|
||||
private static final Properties PROPIEDADES_CONFIGURACION = new Properties();
|
||||
|
||||
private ConfigManager() {}
|
||||
|
||||
static {
|
||||
|
||||
// Obtenemos el Path usando java.nio
|
||||
Path configPath = Paths.get(RUTA_FICHERO_CONFIGURACION);
|
||||
|
||||
// Usamos Files.newInputStream en lugar de FileInputStream
|
||||
try (InputStream is = Files.newInputStream(configPath)) {
|
||||
|
||||
PROPIEDADES_CONFIGURACION.load(is);
|
||||
|
||||
} catch (IOException e) {
|
||||
System.err.println("Error al cargar config/application.properties: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static String getRutaFicheroContinente() {
|
||||
|
||||
/*
|
||||
Una vez que ya has hecho el .load() y el objeto Properties tiene todos los datos cargados,
|
||||
este método .getProperty() -> sirve para extraer la información.
|
||||
Tú le das la "clave" y él te devuelve el "valor", que en este caso sería la ruta del fichero.
|
||||
|
||||
*/
|
||||
|
||||
// Si no encuentra la clave, devuelve la ruta por defecto para que el programa no falle (segundo valor por si acaso falla)
|
||||
return PROPIEDADES_CONFIGURACION.getProperty("ruta.fichero.continente", "C:\\Users\\lauuj\\aadd\\fic07\\informacion_continentes.csv");
|
||||
}
|
||||
|
||||
public static String getSeparadorCsv() {
|
||||
// Si no encuentra la clave, devuelve "#" por defecto
|
||||
return PROPIEDADES_CONFIGURACION.getProperty("separador.csv.continente", "#");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package org.palomafp.aadd.ljl.dao;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.palomafp.aadd.ljl.model.Continente;
|
||||
|
||||
public interface IContinenteDAO {
|
||||
|
||||
public List<Continente> obtenerListaContinentes();
|
||||
|
||||
public Continente obtenerContinentePorCod(String codContinente);
|
||||
|
||||
public boolean insertarContinenteNuevo(Continente continente);
|
||||
|
||||
public boolean eliminarContinente(Continente continente);
|
||||
|
||||
public boolean actualizarContinente(Continente continente);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package org.palomafp.aadd.ljl.dao.impl;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.palomafp.aadd.ljl.config.ConfigManager;
|
||||
import org.palomafp.aadd.ljl.dao.IContinenteDAO;
|
||||
import org.palomafp.aadd.ljl.model.Continente;
|
||||
|
||||
public class ContinenteDaoFichero implements IContinenteDAO {
|
||||
|
||||
// nos evitamos llamar al constructor si hacemos todos los elemntos estáticos (mayor seguridad)
|
||||
// private static final String RUTA_FICHERO = ConfigManager.getRutaFicheroContinente();
|
||||
private static final Path RUTA_FICHERO = Paths.get(ConfigManager.getRutaFicheroContinente());
|
||||
private static final String SEPARADOR = ConfigManager.getSeparadorCsv();
|
||||
|
||||
@Override
|
||||
public List<Continente> obtenerListaContinentes() {
|
||||
|
||||
List<Continente> listaContinentes = new ArrayList<Continente>();
|
||||
//Ya no necesitamos este fichero -> File fichero = new File(RUTA_FICHERO);
|
||||
|
||||
//try (BufferedReader br = new BufferedReader(new FileReader(fichero))){
|
||||
try (BufferedReader br = Files.newBufferedReader(RUTA_FICHERO, StandardCharsets.UTF_8)){
|
||||
|
||||
// Nos saltamos la primera línea que contiene los nombres de los campos.
|
||||
br.readLine();
|
||||
|
||||
String linea;
|
||||
while ((linea=br.readLine()) != null) {
|
||||
|
||||
listaContinentes.add(obtenerObjetoContinente(linea));
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return listaContinentes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Continente obtenerContinentePorCod(String codContinente) {
|
||||
|
||||
Continente continente = null;
|
||||
// File fichero = new File(RUTA_FICHERO);
|
||||
|
||||
//try (BufferedReader br = new BufferedReader(new FileReader(fichero))) {
|
||||
try (BufferedReader br = Files.newBufferedReader(RUTA_FICHERO, StandardCharsets.UTF_8)) {
|
||||
|
||||
br.readLine();
|
||||
|
||||
String linea;
|
||||
while((linea = br.readLine()) != null) {
|
||||
|
||||
continente = obtenerObjetoContinente(linea);
|
||||
|
||||
if (continente.getCodigo().equals(codContinente)) {
|
||||
return continente;
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean insertarContinenteNuevo(Continente continente) {
|
||||
|
||||
//File fichero = new File(RUTA_FICHERO);
|
||||
|
||||
String nuevaLinea = formatearLinea(continente);
|
||||
|
||||
try {
|
||||
//try (BufferedWriter bw = new BufferedWriter(new FileWriter(fichero, true))) {
|
||||
// hacemos el salto de linea -> bw.newLine();
|
||||
//bw.write( "2026" + SEPARADOR + continente.getCodigo() + SEPARADOR + continente.getNombre());
|
||||
|
||||
Files.writeString(RUTA_FICHERO, nuevaLinea, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
|
||||
return true;
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public boolean eliminarContinente(Continente continente) {
|
||||
try {
|
||||
// Leemos todas las líneas
|
||||
List<String> todasLasLineas = Files.readAllLines(RUTA_FICHERO, StandardCharsets.UTF_8);
|
||||
List<String> lineasAConservar = new ArrayList<>();
|
||||
|
||||
for (String linea : todasLasLineas) {
|
||||
|
||||
String lineaTrim = linea.trim();
|
||||
|
||||
if (lineaTrim.isEmpty() || !Character.isDigit(lineaTrim.charAt(0))) {
|
||||
lineasAConservar.add(linea);
|
||||
continue;
|
||||
}
|
||||
|
||||
String[] partes = lineaTrim.split(SEPARADOR);
|
||||
String codContinente = partes[1].trim();
|
||||
|
||||
if (!codContinente.equals(continente.getCodigo())) {
|
||||
lineasAConservar.add(linea);
|
||||
}
|
||||
}
|
||||
|
||||
// Sobrescribimos el archivo (TRUNCATE_EXISTING es el comportamiento por defecto de Files.write)
|
||||
Files.write(RUTA_FICHERO, lineasAConservar, StandardCharsets.UTF_8);
|
||||
return true;
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean actualizarContinente(Continente continente) {
|
||||
try {
|
||||
List<String> todasLasLineas = Files.readAllLines(RUTA_FICHERO, StandardCharsets.UTF_8);
|
||||
List<String> lineasActualizadas = new ArrayList<>();
|
||||
|
||||
for (String linea : todasLasLineas) {
|
||||
|
||||
String lineaTrim = linea.trim();
|
||||
|
||||
if (lineaTrim.isEmpty() || !Character.isDigit(lineaTrim.charAt(0))) {
|
||||
lineasActualizadas.add(linea);
|
||||
continue;
|
||||
}
|
||||
|
||||
String[] partes = lineaTrim.split(SEPARADOR);
|
||||
String codContinente = partes[1].trim();
|
||||
|
||||
if (codContinente.equals(continente.getCodigo())) {
|
||||
|
||||
String nuevaLinea = formatearLinea(continente);
|
||||
lineasActualizadas.add(nuevaLinea);
|
||||
|
||||
} else {
|
||||
lineasActualizadas.add(linea);
|
||||
}
|
||||
}
|
||||
|
||||
// Escribimos la lista completa de nuevo al archivo
|
||||
Files.write(RUTA_FICHERO, lineasActualizadas, StandardCharsets.UTF_8);
|
||||
return true;
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Métodos auxiliares recomendados por la IA:
|
||||
private String formatearLinea(Continente continente) {
|
||||
|
||||
String anioActual = String.valueOf(LocalDate.now().getYear());
|
||||
return anioActual + SEPARADOR + continente.getCodigo() + SEPARADOR + continente.getNombre();
|
||||
}
|
||||
|
||||
private Continente obtenerObjetoContinente(String linea) {
|
||||
|
||||
String[] partes = linea.split(SEPARADOR);
|
||||
Continente continente = new Continente();
|
||||
|
||||
continente.setCodigo(partes[1].trim());
|
||||
continente.setNombre(partes[2].trim());
|
||||
|
||||
return continente;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package org.palomafp.aadd.ljl.model;
|
||||
|
||||
public class Continente {
|
||||
|
||||
private String codigo;
|
||||
private String nombre;
|
||||
|
||||
// Constructores
|
||||
public Continente() {
|
||||
|
||||
}
|
||||
public Continente(String codigo, String nombre) {
|
||||
super();
|
||||
this.codigo = codigo;
|
||||
this.nombre = nombre;
|
||||
}
|
||||
|
||||
|
||||
// Getters y setters
|
||||
public String getCodigo() {
|
||||
return codigo;
|
||||
}
|
||||
public String getNombre() {
|
||||
return nombre;
|
||||
}
|
||||
|
||||
public void setCodigo(String codigo) {
|
||||
this.codigo = codigo;
|
||||
}
|
||||
public void setNombre(String nombre) {
|
||||
this.nombre = nombre;
|
||||
}
|
||||
|
||||
// Generamos el método toString
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Continente [codigo=" + codigo + ", nombre=" + nombre + "]";
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user