Actividad 1.9
This commit is contained in:
+10
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-25">
|
||||
<attributes>
|
||||
<attribute name="module" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="src" path="src"/>
|
||||
<classpathentry kind="output" path="bin"/>
|
||||
</classpath>
|
||||
@@ -0,0 +1,28 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>Ficheros_09</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.jdt.core.javabuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>org.eclipse.jdt.core.javanature</nature>
|
||||
</natures>
|
||||
<filteredResources>
|
||||
<filter>
|
||||
<id>1791905344202</id>
|
||||
<name></name>
|
||||
<type>30</type>
|
||||
<matcher>
|
||||
<id>org.eclipse.core.resources.regexFilterMatcher</id>
|
||||
<arguments>node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
|
||||
</matcher>
|
||||
</filter>
|
||||
</filteredResources>
|
||||
</projectDescription>
|
||||
@@ -0,0 +1,2 @@
|
||||
eclipse.preferences.version=1
|
||||
encoding/<project>=UTF-8
|
||||
@@ -0,0 +1,11 @@
|
||||
eclipse.preferences.version=1
|
||||
org.eclipse.jdt.core.compiler.codegen.targetPlatform=25
|
||||
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
|
||||
org.eclipse.jdt.core.compiler.compliance=25
|
||||
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
|
||||
org.eclipse.jdt.core.compiler.debug.localVariable=generate
|
||||
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
|
||||
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
|
||||
org.eclipse.jdt.core.compiler.release=enabled
|
||||
org.eclipse.jdt.core.compiler.source=25
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,9 @@
|
||||
# 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/aleja/aadd/fic05/informacion_continentes.csv
|
||||
continente.csv.separador=#
|
||||
|
||||
pais.ruta.fichero=C:/Users/aleja/aadd/fic05/informacion_paises.txt
|
||||
pais.txt.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,15 @@
|
||||
package org.palomafp.aadd.aez.dao;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.palomafp.aadd.aez.model.Pais;
|
||||
|
||||
public interface IPaisDAO {
|
||||
List<Pais> obtenerTodos();
|
||||
|
||||
Pais obtenerPorId(int identificador);
|
||||
|
||||
List<Pais> obtenerPorContinente(String codigoContinente);
|
||||
|
||||
boolean insertar(Pais pais);
|
||||
}
|
||||
@@ -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,111 @@
|
||||
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.dao.IPaisDAO;
|
||||
import org.palomafp.aadd.aez.gestores.GestorConfiguracion;
|
||||
import org.palomafp.aadd.aez.model.Continente;
|
||||
import org.palomafp.aadd.aez.model.Pais;
|
||||
|
||||
public class PaisDaoFichero implements IPaisDAO {
|
||||
|
||||
private final Path rutaFichero;
|
||||
private final String separador;
|
||||
private final IContinenteDAO continenteDAO;
|
||||
|
||||
public PaisDaoFichero() {
|
||||
String ruta = GestorConfiguracion.getProperty("pais.ruta.fichero", "config/informacion_paises.txt");
|
||||
this.rutaFichero = Paths.get(ruta);
|
||||
this.separador = GestorConfiguracion.getProperty("pais.txt.separador", "#");
|
||||
this.continenteDAO = new ContinenteDaoCSV();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Pais> obtenerTodos() {
|
||||
List<Pais> paises = new ArrayList<>();
|
||||
|
||||
if (!Files.exists(rutaFichero)) {
|
||||
return paises;
|
||||
}
|
||||
|
||||
try {
|
||||
List<String> lineas = Files.readAllLines(rutaFichero, StandardCharsets.UTF_8);
|
||||
for (String linea : lineas) {
|
||||
if (linea.trim().isEmpty() || linea.trim().startsWith("#")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String[] datos = linea.split(separador);
|
||||
if (datos.length >= 4) {
|
||||
int id = Integer.parseInt(datos[0].trim());
|
||||
String nombre = datos[1].trim();
|
||||
String capital = datos[2].trim();
|
||||
String codContinente = datos[3].trim();
|
||||
|
||||
Continente c = continenteDAO.obtenerPorCodigo(codContinente);
|
||||
if (c == null) {
|
||||
c = new Continente(codContinente, null);
|
||||
}
|
||||
|
||||
paises.add(new Pais(id, nombre, capital, c));
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
System.err.println("Error al leer el fichero de países: " + e.getMessage());
|
||||
} catch (NumberFormatException e) {
|
||||
System.err.println("Error en formato numérico: " + e.getMessage());
|
||||
}
|
||||
|
||||
return paises;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Pais obtenerPorId(int identificador) {
|
||||
for (Pais p : obtenerTodos()) {
|
||||
if (p.getIdentificador() == identificador) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Pais> obtenerPorContinente(String codigoContinente) {
|
||||
List<Pais> resultado = new ArrayList<>();
|
||||
for (Pais p : obtenerTodos()) {
|
||||
if (p.getContinente() != null && p.getContinente().getCodigo() != null
|
||||
&& p.getContinente().getCodigo().equalsIgnoreCase(codigoContinente)) {
|
||||
resultado.add(p);
|
||||
}
|
||||
}
|
||||
return resultado;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean insertar(Pais pais) {
|
||||
if (pais == null || pais.getContinente() == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String codContinente = pais.getContinente().getCodigo();
|
||||
String nuevaLinea = pais.getIdentificador() + separador + pais.getNombre() + separador + pais.getCapital()
|
||||
+ separador + codContinente + System.lineSeparator();
|
||||
|
||||
try {
|
||||
Files.writeString(rutaFichero, nuevaLinea, StandardCharsets.UTF_8, StandardOpenOption.CREATE,
|
||||
StandardOpenOption.APPEND);
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
System.err.println("Error al insertar país: " + 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 + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package org.palomafp.aadd.aez.model;
|
||||
|
||||
public class Pais {
|
||||
private int identificador;
|
||||
private String nombre;
|
||||
private String capital;
|
||||
private Continente continente;
|
||||
|
||||
public Pais() {
|
||||
}
|
||||
|
||||
public Pais(int identificador, String nombre, String capital, Continente continente) {
|
||||
this.identificador = identificador;
|
||||
this.nombre = nombre;
|
||||
this.capital = capital;
|
||||
this.continente = continente;
|
||||
}
|
||||
|
||||
// Getters y Setters
|
||||
public int getIdentificador() {
|
||||
return identificador;
|
||||
}
|
||||
|
||||
public void setIdentificador(int identificador) {
|
||||
this.identificador = identificador;
|
||||
}
|
||||
|
||||
public String getNombre() {
|
||||
return nombre;
|
||||
}
|
||||
|
||||
public void setNombre(String nombre) {
|
||||
this.nombre = nombre;
|
||||
}
|
||||
|
||||
public String getCapital() {
|
||||
return capital;
|
||||
}
|
||||
|
||||
public void setCapital(String capital) {
|
||||
this.capital = capital;
|
||||
}
|
||||
|
||||
public Continente getContinente() {
|
||||
return continente;
|
||||
}
|
||||
|
||||
public void setContinente(Continente continente) {
|
||||
this.continente = continente;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
String nomContinente = (continente != null && continente.getNombre() != null) ? continente.getNombre() : "";
|
||||
String codContinente = (continente != null) ? continente.getCodigo() : "";
|
||||
|
||||
return nombre + " (" + identificador + ") con capital en " + capital + " pertenece al continente "
|
||||
+ nomContinente + " (" + codContinente + ")";
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user