Entrega Actividad 1.6: patrón DAO→ CRUD (Continente)
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,8 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
/**
|
||||
*
|
||||
*/
|
||||
module Ficheros_03 {
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package org.palomafp.aadd.ljl;
|
||||
|
||||
import java.util.ArrayList;
|
||||
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 AppPrincipal {
|
||||
|
||||
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]);
|
||||
|
||||
// para ir más rápido con las pruebas -> int opcion = 5;
|
||||
|
||||
IContinenteDAO continenteDao = new ContinenteDaoFichero();
|
||||
Continente continente;
|
||||
|
||||
switch(opcion) {
|
||||
|
||||
case 1:
|
||||
// Obtenemos una Lista de continentes
|
||||
List<Continente> continentes = continenteDao.obtenerListaContinentes();
|
||||
|
||||
for (Continente cont : continentes) {
|
||||
System.out.println(cont);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 2:
|
||||
// Obtenemos un Continente por su código
|
||||
continente = continenteDao.obtenerContinentePorCod(args[1]);
|
||||
System.out.println("El continente que buscas es: " + continente);
|
||||
break;
|
||||
|
||||
case 3:
|
||||
// Insertaremos un continente
|
||||
continente = new Continente(args[1], args[2]);
|
||||
continenteDao.insertarContinenteNuevo(continente);
|
||||
break;
|
||||
|
||||
case 4:
|
||||
// Eliminaremos un continente
|
||||
continente = new Continente(args[1], args[2]);
|
||||
continenteDao.eliminarContinente(continente);
|
||||
break;
|
||||
|
||||
case 5:
|
||||
// Actualizaremos un continente
|
||||
continente = new Continente(args[1], args[2]);
|
||||
continenteDao.actualizarContinente(continente);
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
System.out.println("Opción no esperada");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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,254 @@
|
||||
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.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.palomafp.aadd.ljl.dao.IContinenteDAO;
|
||||
import org.palomafp.aadd.ljl.model.Continente;
|
||||
|
||||
public class ContinenteDaoFichero implements IContinenteDAO {
|
||||
|
||||
private static final String RUTA ="C:\\Users\\lauuj\\aadd\\fic06\\informacion_continentes.csv";
|
||||
// Hacemos estático tambien el separador por no cambiar en varios sitios si se cambia de fichero
|
||||
private static final String SEPARADOR = "#";
|
||||
|
||||
@Override
|
||||
public List<Continente> obtenerListaContinentes() {
|
||||
|
||||
List<Continente> continentes = new ArrayList<Continente>();
|
||||
File fichero = new File(RUTA);
|
||||
|
||||
try (BufferedReader br = new BufferedReader(new FileReader(fichero))){
|
||||
|
||||
String linea;
|
||||
while ((linea=br.readLine()) != null) {
|
||||
|
||||
linea.trim(); // le quitamos los posibles espacios en blanco
|
||||
|
||||
// Si la línea está vacía o no empieza por un número, saltamos
|
||||
if (linea.isEmpty() || !Character.isDigit(linea.charAt(0))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// el csv tiene en cada linea un # para separar el contenido
|
||||
String[] partes = linea.split(SEPARADOR);
|
||||
|
||||
// no incluimos el año porque no se especifica
|
||||
if (partes.length == 3) {
|
||||
continentes.add(new Continente(partes[1].trim(), partes[2].trim()));
|
||||
}
|
||||
}
|
||||
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return continentes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Continente obtenerContinentePorCod(String codContinente) {
|
||||
File fichero = new File(RUTA);
|
||||
|
||||
try (BufferedReader br = new BufferedReader(new FileReader(fichero))) {
|
||||
|
||||
String linea;
|
||||
|
||||
while((linea = br.readLine()) != null) {
|
||||
|
||||
linea = linea.trim();
|
||||
|
||||
if (linea.isEmpty() || !Character.isDigit(linea.charAt(0))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String[] partes = linea.split(SEPARADOR);
|
||||
String codigoFichero = partes[1].trim();
|
||||
|
||||
if (codigoFichero.equals(codContinente)) {
|
||||
|
||||
Continente continente = new Continente();
|
||||
continente.setCodigo(codigoFichero);
|
||||
continente.setNombre(partes[2].trim());
|
||||
|
||||
return continente;
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.getMessage();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean insertarContinenteNuevo(Continente continente) {
|
||||
|
||||
// comprobación de que el codigo del continente o el nombre no existe en el fichero
|
||||
List<Continente> continentes = obtenerListaContinentes();
|
||||
|
||||
for (Continente cont: continentes) {
|
||||
if (continente.getCodigo().equals(cont.getCodigo()) || continente.getNombre().equals(cont.getNombre()) ) {
|
||||
System.out.println("Has introducido un parametro ya que existe. No se puede insertar");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ya sabemos que no existe asi que lo creamos
|
||||
File fichero = new File(RUTA);
|
||||
|
||||
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());
|
||||
|
||||
System.out.println("Linea insertada correctamente");
|
||||
|
||||
return true;
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public boolean eliminarContinente(Continente continente) {
|
||||
|
||||
// 1. comprobación de que si que existe el continente
|
||||
if (obtenerContinentePorCod(continente.getCodigo()) == null) {
|
||||
System.out.println("El continente no existe. No se puede eliminar");
|
||||
return false;
|
||||
}
|
||||
|
||||
File fichero = new File(RUTA);
|
||||
List<String> lineasAConservar = new ArrayList<>();
|
||||
|
||||
// 2. Leemos el archivo y guardamos todo EXCEPTO el continente a borrar
|
||||
try (BufferedReader br = new BufferedReader(new FileReader(fichero))) {
|
||||
String linea;
|
||||
|
||||
while ((linea = br.readLine()) != null) {
|
||||
String lineaTrim = linea.trim();
|
||||
|
||||
// Si la línea está vacía o es una cabecera, la conservamos tal cual
|
||||
if (lineaTrim.isEmpty() || !Character.isDigit(lineaTrim.charAt(0))) {
|
||||
lineasAConservar.add(linea);
|
||||
continue;
|
||||
}
|
||||
|
||||
String[] partes = lineaTrim.split(SEPARADOR);
|
||||
String codContinente = partes[1].trim();
|
||||
|
||||
// Si el código NO coincide, guardamos la línea. Si coincide, la ignoramos (se elimina)
|
||||
if (!codContinente.equals(continente.getCodigo())) {
|
||||
lineasAConservar.add(linea);
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
// 3. Sobrescribimos el fichero completo con las lineas de la lista
|
||||
// FileWriter con parámetro 'false' (o sin él) sobrescribe el fichero desde 0 (se vacía)
|
||||
try (BufferedWriter bw = new BufferedWriter(new FileWriter(fichero, false))) {
|
||||
|
||||
for (int i = 0; i < lineasAConservar.size(); i++) {
|
||||
|
||||
// seleccionamos una a una las lineas de la lista que guarda las lineas no borradas
|
||||
bw.write(lineasAConservar.get(i));
|
||||
|
||||
/* Como tenemos que hacer un salto de linea por cada linea que escribamos (para que no se apelotonen)
|
||||
hay que tener en cuenta que luego no queremos dejar un espacio en blanco al final del csv
|
||||
por lo que solo metemos el salto de linea hasta la penultima linea incluida (lineasAConservar.size() - 1)
|
||||
*/
|
||||
if (i < lineasAConservar.size() - 1) {
|
||||
bw.newLine();
|
||||
}
|
||||
}
|
||||
System.out.println("Continente eliminado correctamente.");
|
||||
return true;
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public boolean actualizarContinente(Continente continente) {
|
||||
// 1. Comprobamos si existe el continente para actualizarlo
|
||||
if (obtenerContinentePorCod(continente.getCodigo()) == null) {
|
||||
System.out.println("El continente no existe. No se puede actualizar.");
|
||||
return false;
|
||||
}
|
||||
|
||||
File fichero = new File(RUTA);
|
||||
List<String> lineasActualizadas = new ArrayList<>();
|
||||
|
||||
// 2. Leemos y modificamos solo la línea que coincida
|
||||
try (BufferedReader br = new BufferedReader(new FileReader(fichero))) {
|
||||
String linea;
|
||||
|
||||
while ((linea = br.readLine()) != null) {
|
||||
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())) {
|
||||
// Reconstruimos la línea: partes[0] (año) + partes[1](código) + nombre NUEVO
|
||||
String nuevaLinea = partes[0] + SEPARADOR + partes[1] + SEPARADOR + continente.getNombre();
|
||||
lineasActualizadas.add(nuevaLinea);
|
||||
} else {
|
||||
// Las demás líneas se quedan como estaban
|
||||
lineasActualizadas.add(linea);
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
|
||||
// 3. Sobrescribimos el fichero
|
||||
try (BufferedWriter bw = new BufferedWriter(new FileWriter(fichero, false))) {
|
||||
for (int i = 0; i < lineasActualizadas.size(); i++) {
|
||||
|
||||
// cogemos de la lista de lineas una
|
||||
bw.write(lineasActualizadas.get(i));
|
||||
|
||||
// hacemos el salto de linea (salvo que sea la última línea)
|
||||
if (i < lineasActualizadas.size() - 1) {
|
||||
bw.newLine();
|
||||
}
|
||||
}
|
||||
System.out.println("Continente actualizado correctamente.");
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -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