Actividad 1.8
This commit is contained in:
+16
@@ -0,0 +1,16 @@
|
|||||||
|
# Eclipse
|
||||||
|
.classpath
|
||||||
|
.project
|
||||||
|
.settings/
|
||||||
|
|
||||||
|
# Compilación Java
|
||||||
|
bin/
|
||||||
|
target/
|
||||||
|
*.class
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# Sistema operativo
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# Elegir nombres de entradas que sean SIGNIFICATIVOS
|
||||||
|
# y que no se repitan con otras entradas de la misma aplicación
|
||||||
|
|
||||||
|
# Información relativa Continentes
|
||||||
|
continente.ruta.fichero=C:\\Users\\ineva\\INM\\tmp\\aadd\\fic06\\informacion_continentes.csv
|
||||||
|
continente.csv.separador=#
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package org.palomafp.aadd.aez;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.palomafp.aadd.aez.dao.IContinenteDAO;
|
||||||
|
import org.palomafp.aadd.aez.dao.impl.ContinenteDaoCSV;
|
||||||
|
import org.palomafp.aadd.aez.model.Continente;
|
||||||
|
|
||||||
|
public class GestorMapaMundi {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
// Inicia el DAO utilizando el principio de polimorfismo (interfaz
|
||||||
|
// IContinenteDAO)
|
||||||
|
IContinenteDAO continenteDao = new ContinenteDaoCSV();
|
||||||
|
|
||||||
|
System.out.println("--- Lectura de Continentes con java.nio ---");
|
||||||
|
// Llama al método para obtener la lista de continentes desde el archivo CSV
|
||||||
|
List<Continente> lista = continenteDao.obtenerTodos();
|
||||||
|
|
||||||
|
// Recorre la lista e imprime cada continente llamando a su método toString()
|
||||||
|
for (Continente c : lista) {
|
||||||
|
System.out.println(c);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prueba de inserción de un nuevo registro utilizando java.nio
|
||||||
|
Continente nuevoContinente = new Continente("AN", "Antártida");
|
||||||
|
if (continenteDao.insertar(nuevoContinente)) {
|
||||||
|
System.out.println("\nNuevo continente insertado correctamente.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package org.palomafp.aadd.aez.dao;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.palomafp.aadd.aez.model.Continente;
|
||||||
|
|
||||||
|
public interface IContinenteDAO {
|
||||||
|
// Firma del método para recuperar todos los continentes de la fuente de datos
|
||||||
|
List<Continente> obtenerTodos();
|
||||||
|
|
||||||
|
// Firma del método para buscar un continente por su código identificador
|
||||||
|
Continente obtenerPorCodigo(String codigo);
|
||||||
|
|
||||||
|
// Firma del método para guardar un nuevo continente en la fuente de datos
|
||||||
|
boolean insertar(Continente continente);
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package org.palomafp.aadd.aez.dao.impl;
|
||||||
|
|
||||||
|
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.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.palomafp.aadd.aez.dao.IContinenteDAO;
|
||||||
|
import org.palomafp.aadd.aez.gestores.GestorConfiguracion;
|
||||||
|
import org.palomafp.aadd.aez.model.Continente;
|
||||||
|
|
||||||
|
// Implementación de la interfaz DAO orientada a ficheros CSV utilizando el paquete java.nio
|
||||||
|
public class ContinenteDaoCSV implements IContinenteDAO {
|
||||||
|
|
||||||
|
// Ruta del fichero gestionada mediante java.nio.file.Path en lugar de
|
||||||
|
// java.io.File
|
||||||
|
private final Path rutaFichero;
|
||||||
|
// Carácter delimitador o separador de campos del archivo CSV
|
||||||
|
private final String separadorCsv;
|
||||||
|
|
||||||
|
// Constructor: recupera las propiedades de configuración dinámicamente
|
||||||
|
public ContinenteDaoCSV() {
|
||||||
|
// Obtiene la ruta del fichero de configuración o usa la ruta por defecto
|
||||||
|
String ruta = GestorConfiguracion.getProperty("continente.fichero.ruta", "config/informacion_continentes.csv");
|
||||||
|
// Convierte la cadena de texto en un objeto Path con Paths.get()
|
||||||
|
this.rutaFichero = Paths.get(ruta);
|
||||||
|
// Obtiene el separador de campos desde el gestor de configuración
|
||||||
|
this.separadorCsv = GestorConfiguracion.getProperty("continente.fichero.separador", ";");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lee todos los registros del fichero CSV y los devuelve como una lista de
|
||||||
|
// objetos Continente
|
||||||
|
@Override
|
||||||
|
public List<Continente> obtenerTodos() {
|
||||||
|
List<Continente> continentes = new ArrayList<>();
|
||||||
|
|
||||||
|
// Verifica la existencia del archivo mediante la clase utilitaria Files de
|
||||||
|
// java.nio
|
||||||
|
if (!Files.exists(rutaFichero)) {
|
||||||
|
return continentes;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Files.readAllLines(): lee todas las líneas del fichero en memoria de un solo
|
||||||
|
// paso usando UTF-8
|
||||||
|
List<String> lineas = Files.readAllLines(rutaFichero, StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
// Recorre cada línea leída
|
||||||
|
for (String linea : lineas) {
|
||||||
|
// Omite líneas vacías o espacios en blanco
|
||||||
|
if (linea.trim().isEmpty())
|
||||||
|
continue;
|
||||||
|
|
||||||
|
// Divide la línea según el separador configurado (por ejemplo ';')
|
||||||
|
String[] datos = linea.split(separadorCsv);
|
||||||
|
|
||||||
|
// Valida que la línea tenga al menos código y nombre
|
||||||
|
if (datos.length >= 2) {
|
||||||
|
// Crea la instancia de Continente eliminando espacios innecesarios
|
||||||
|
Continente c = new Continente(datos[0].trim(), datos[1].trim());
|
||||||
|
// Añade el objeto a la lista
|
||||||
|
continentes.add(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("Error al leer el fichero CSV con java.nio: " + e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return continentes;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Busca un continente en la lista mediante su código identificador
|
||||||
|
@Override
|
||||||
|
public Continente obtenerPorCodigo(String codigo) {
|
||||||
|
// Reutiliza obtenerTodos() para buscar en la lista recuperada
|
||||||
|
for (Continente c : obtenerTodos()) {
|
||||||
|
// Compara los códigos ignorando mayúsculas y minúsculas
|
||||||
|
if (c.getCodigo().equalsIgnoreCase(codigo)) {
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null; // Devuelve null si no se encuentra
|
||||||
|
}
|
||||||
|
|
||||||
|
// Añade una nueva entidad Continente al final del fichero CSV
|
||||||
|
@Override
|
||||||
|
public boolean insertar(Continente continente) {
|
||||||
|
// Validación previa del objeto antes de insertar
|
||||||
|
if (continente == null || continente.getCodigo() == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Construye la línea formateada en CSV agregando el salto de línea según el SO
|
||||||
|
// (System.lineSeparator())
|
||||||
|
String nuevaLinea = continente.getCodigo() + separadorCsv + continente.getNombre() + System.lineSeparator();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Files.writeString(): escribe la nueva línea en el archivo usando java.nio
|
||||||
|
// StandardOpenOption.CREATE: crea el fichero si no existe
|
||||||
|
// StandardOpenOption.APPEND: añade el contenido al final sin sobrescribir las
|
||||||
|
// líneas existentes
|
||||||
|
Files.writeString(rutaFichero, nuevaLinea, StandardCharsets.UTF_8, StandardOpenOption.CREATE,
|
||||||
|
StandardOpenOption.APPEND);
|
||||||
|
return true;
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("Error al insertar con java.nio: " + e.getMessage());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package org.palomafp.aadd.aez.gestores;
|
||||||
|
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
public class GestorConfiguracion {
|
||||||
|
// Objeto Properties que almacena en memoria los pares clave-valor leídos del archivo
|
||||||
|
private static final Properties properties = new Properties();
|
||||||
|
|
||||||
|
// Ruta relativa donde se ubica el fichero de configuración
|
||||||
|
private static final String RUTA_CONFIG = "config/application.properties";
|
||||||
|
|
||||||
|
// Bloque estático: se ejecuta automáticamente una sola vez cuando la JVM carga
|
||||||
|
// esta clase en memoria
|
||||||
|
static {
|
||||||
|
// try-with-resources con FileInputStream: asegura el cierre automático del InputStream al finalizar
|
||||||
|
try (InputStream input = new FileInputStream(RUTA_CONFIG)) {
|
||||||
|
// Carga todas las propiedades del fichero en el objeto 'properties'
|
||||||
|
properties.load(input);
|
||||||
|
} catch (IOException e) {
|
||||||
|
// Muestra mensaje de error en la consola de errores si no se encuentra o no se
|
||||||
|
// puede leer el archivo
|
||||||
|
System.err.println("Error al cargar el archivo de configuración: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Devuelve el valor asociado a la clave recibida por parámetro
|
||||||
|
public static String getProperty(String clave) {
|
||||||
|
return properties.getProperty(clave);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Devuelve el valor asociado a la clave, o el valorPorDefecto si la clave no existe en el fichero
|
||||||
|
public static String getProperty(String clave, String valorPorDefecto) {
|
||||||
|
return properties.getProperty(clave, valorPorDefecto);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package org.palomafp.aadd.aez.model;
|
||||||
|
|
||||||
|
public class Continente {
|
||||||
|
private String codigo;
|
||||||
|
private String nombre;
|
||||||
|
|
||||||
|
public Continente() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Continente(String codigo, String nombre) {
|
||||||
|
this.codigo = codigo;
|
||||||
|
this.nombre = nombre;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCodigo() {
|
||||||
|
return codigo;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCodigo(String codigo) {
|
||||||
|
this.codigo = codigo;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getNombre() {
|
||||||
|
return nombre;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setNombre(String nombre) {
|
||||||
|
this.nombre = nombre;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Continente [codigo=" + codigo + ", nombre=" + nombre + "]";
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user