Ejercicio B Completos

This commit is contained in:
2024-05-26 18:43:25 +02:00
parent 03e9a9c007
commit f7a6e9beab
43 changed files with 595 additions and 9 deletions

View File

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 37 KiB

View File

Before

Width:  |  Height:  |  Size: 371 KiB

After

Width:  |  Height:  |  Size: 371 KiB

View File

Before

Width:  |  Height:  |  Size: 531 KiB

After

Width:  |  Height:  |  Size: 531 KiB

View File

Before

Width:  |  Height:  |  Size: 88 KiB

After

Width:  |  Height:  |  Size: 88 KiB

View File

Before

Width:  |  Height:  |  Size: 222 KiB

After

Width:  |  Height:  |  Size: 222 KiB

View File

Before

Width:  |  Height:  |  Size: 107 KiB

After

Width:  |  Height:  |  Size: 107 KiB

View File

Before

Width:  |  Height:  |  Size: 232 KiB

After

Width:  |  Height:  |  Size: 232 KiB

View File

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 23 KiB

View File

Before

Width:  |  Height:  |  Size: 527 KiB

After

Width:  |  Height:  |  Size: 527 KiB

View File

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 39 KiB

View File

Before

Width:  |  Height:  |  Size: 119 KiB

After

Width:  |  Height:  |  Size: 119 KiB

View File

Before

Width:  |  Height:  |  Size: 114 KiB

After

Width:  |  Height:  |  Size: 114 KiB

1
Documentos/tareas.json Normal file
View File

@@ -0,0 +1 @@
[{"id":3,"description":"Aprender Java","priority":2,"completed":false},{"id":5,"description":"Aprender JSON","priority":3,"completed":false},{"id":6,"description":"Aprender GSON","priority":3,"completed":false},{"id":10,"description":"Desaprender lo aprendido","priority":1,"completed":false}]

15
pom.xml
View File

@@ -14,6 +14,8 @@
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
@@ -21,6 +23,19 @@
<version>5.9.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>utilidades</groupId>
<artifactId>persona</artifactId>
<scope>system</scope>
<version>1.0</version>
<systemPath>${basedir}/Documentos/Persona.jar</systemPath>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
<build>

View File

@@ -12,7 +12,7 @@ public class Ejercicio_B1 {
// try-for-resources
try (Scanner lector=new Scanner(Ejercicio_B1.class.getResourceAsStream("Documentos/numeros.txt"))){
// Alternatica a try-for-res
// Alternativa a try-for-res
// File f = new File("Documentos/numeros.txt");
// Scanner lector = new Scanner(f);

View File

@@ -0,0 +1,51 @@
package iesthiar;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* Ejercicio sobre properties
*/
public class Ejercicio_B10 {
public static void main(String[] args) {
ConfigManager configuracion=new ConfigManager();
try {
configuracion.loadConfig();
} catch (IOException e) {
System.err.println(e.getMessage());
}
System.out.println("Empresa: "+configuracion.getNombreEmpresa());
System.out.println("Intentos máximos: "+configuracion.getMaxIntentos());
System.out.println("Tiempo de sesión: "+configuracion.getSesionTimeout());
}
}
class ConfigManager {
private Properties config;
public ConfigManager(){
config = new Properties();
}
public void loadConfig() throws IOException{
try (FileInputStream fichero=new FileInputStream("Documentos/config.properties")){
config.load(fichero);
} catch (IOException e) {
System.out.println("Se ha producido un error al leer el fichero de configuración");
throw e;
}
}
public String getNombreEmpresa(){
return config.getProperty("empresa.nombre");
}
public int getMaxIntentos(){
return Integer.parseInt(config.getProperty("login.max_intentos"));
}
public int getSesionTimeout(){
return Integer.parseInt(config.getProperty("sesion.timeout"));
}
}

View File

@@ -0,0 +1,140 @@
package iesthiar;
/**
* Buscamos la última versión de la libreria gson en maven repository y la incorporamos al proyecto
*/
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class Ejercicio_B11 {
public static void main(String[] args) {
TaskManager listaTareas=new TaskManager();
// Cambiamos el valos de esta variable para leer o escribir
boolean escribir=false;
if (escribir) {
listaTareas.addTask(new Task(3, "Aprender Java", 2));
listaTareas.addTask(new Task(5, "Aprender JSON", 3));
listaTareas.addTask(new Task(6, "Aprender GSON", 3));
listaTareas.addTask(new Task(10, "Desaprender lo aprendido", 1));
listaTareas.saveTasksToFile("Documentos/tareas.json");
System.out.println("Fichero guardado correctamente");
} else {
// Segunda parte, recuperamos el fichero
listaTareas.loadTasksFromFile("Documentos/tareas.json");
listaTareas.mostrarTareas();
}
}
}
class Task{
private int id;
private String description;
private int priority;
private boolean completed;
public Task(int id, String description, int priority) {
this.id = id;
this.description = description;
setPriority(priority);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
if (priority>=1 && priority<=3)
this.priority = priority;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
@Override
public String toString() {
return "Task{" +
"id=" + id +
", description='" + description + '\'' +
", priority=" + priority +
", completed=" + completed +
'}';
}
}
class TaskManager{
private List<Task> lista=new ArrayList<>();
public void addTask(Task task){
lista.add(task);
}
public void removeTask(int id){
lista.removeIf(task -> task.getId()==id);
}
public Task getTask(int id){
return lista.stream().filter(task -> task.getId()==id)
.findFirst()
.orElse(null);
}
public void saveTasksToFile(String fileName){
Gson gson=new Gson();
try (FileWriter writer=new FileWriter(fileName)){
writer.write(gson.toJson(lista));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void loadTasksFromFile(String fileName){
Gson gson=new Gson();
Type tipoListaPersonas = new TypeToken<ArrayList<Task>>(){}.getType();
try (FileReader reader=new FileReader(fileName)){
lista=gson.fromJson(reader,tipoListaPersonas);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void mostrarTareas(){
for (Task task : lista) {
System.out.println(task);
}
}
}

View File

@@ -0,0 +1,77 @@
package iesthiar;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
/**
* Implementa un programa que muestre por pantalla los valores máximos y mínimos del archivo numeros.txt.
*
*/
public class Ejercicio_B1v2 {
public static void main(String[] args) {
int minimo=Integer.MAX_VALUE;
int maximo=Integer.MIN_VALUE;
// Leer de un fichero. Ruta relativa
File fichero=new File("Documentos/numeros.txt");
// Usamos try-for-resources. No hace falta cerrar, se cierra solo
try (Scanner entrada=new Scanner(fichero)){
// Leemos mientras tengamos datos
while (entrada.hasNext()) {
int numero=entrada.nextInt();
if (numero<minimo)
minimo=numero;
if (numero>maximo)
maximo=numero;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.printf("Con Scanner: El mínimo es %d y el máximo es %d%n",minimo,maximo);
// Usando FileReader/BufferedReader
minimo=Integer.MAX_VALUE;
maximo=Integer.MIN_VALUE;
try (BufferedReader br = new BufferedReader(new FileReader("Documentos/numeros.txt"))) {
String linea;
while ((linea = br.readLine()) != null) {
int numero=Integer.parseInt(linea);
if (numero<minimo)
minimo=numero;
if (numero>maximo)
maximo=numero;
}
} catch (IOException e) {
System.err.println("Error al leer el archivo: " + e.getMessage());
}
System.out.printf("Con FileReader/BufferedReader: El mínimo es %d y el máximo es %d%n",minimo,maximo);
//Usando nio
minimo=Integer.MAX_VALUE;
maximo=Integer.MIN_VALUE;
Path path = Paths.get("Documentos/numeros.txt");
try {
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
int numero=Integer.parseInt(line);
if (numero<minimo)
minimo=numero;
if (numero>maximo)
maximo=numero;
}
} catch (IOException ex) {
System.err.println("Error al leer el archivo: " + ex.getMessage());
}
System.out.printf("Con nio: El mínimo es %d y el máximo es %d%n",minimo,maximo);
}
}

View File

@@ -0,0 +1,41 @@
package iesthiar;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Ejercicio_B2ConMapa {
public static void main(String[] args) {
HashMap<String,Double> alumnos=new HashMap<>();
File fichero=new File("Documentos/alumnos_notas.txt");
try (Scanner entrada=new Scanner(fichero)){
while (entrada.hasNextLine()) {
String[] linea=entrada.nextLine().split(" ");
double notaMedia=0;
for (int i=2;i<linea.length;i++) {
notaMedia+=Integer.parseInt(linea[i]);
}
alumnos.put(linea[0]+" "+linea[1],notaMedia/(linea.length-2));
}
}
catch (FileNotFoundException e) {
System.err.println("Error al leer el fichero. "+e.getMessage());
}
ArrayList<Map.Entry<String,Double>> entradas=new ArrayList<>(alumnos.entrySet());
entradas.sort(new Comparator<Map.Entry<String, Double>>() {
@Override
public int compare(Map.Entry<String, Double> e1, Map.Entry<String, Double> e2) {
return e2.getValue().compareTo(e1.getValue());
}
});
for (Map.Entry<String, Double> entrada : entradas) {
System.out.printf("%.2f - %s%n",entrada.getValue(),entrada.getKey());
}
}
}

View File

@@ -0,0 +1,70 @@
package iesthiar;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
/*
El archivo alumnos_notas.txt contiene una lista de 10 alumnos y las notas que han obtenido en cada
asignatura. El número de asignaturas de cada alumno es variable. Implementa un programa que muestre
por pantalla la nota media de cada alumno junto a su nombre y apellido, ordenado por nota media de
mayor a menor.
Formato entrada: Joanna Rogers 10 0 8 6 2 9 (nombre apellido <lista notas>)
*/
public class Ejercicio_B2v2 {
public static void main(String[] args) {
ArrayList<Alumno> alumnos=new ArrayList<>();
File fichero=new File("Documentos/alumnos_notas.txt");
// Try con recursos. Aquellos recursos que implementan Autocloseable o Closeable
// pueden definirse en el try y se cerrarán automáticamente
// mas: https://picodotdev.github.io/blog-bitix/2018/04/la-sentencia-try-with-resources-de-java/
try (Scanner entrada=new Scanner(fichero)){
while (entrada.hasNextLine()) {
String[] linea=entrada.nextLine().split(" ");
double notaMedia=0;
for (int i=2;i<linea.length;i++) {
notaMedia+=Integer.parseInt(linea[i]);
}
alumnos.add(new Alumno(linea[0]+" "+linea[1],notaMedia/(linea.length-2)));
}
}
catch (FileNotFoundException e) {
System.err.println("Error al leer el fichero. "+e.getMessage());
}
// Al salir del try se cierra automáticamente el recurso
Collections.sort(alumnos,Collections.reverseOrder());
for (Alumno a: alumnos) {
System.out.println(a);
}
}
}
class Alumno implements Comparable<Alumno>{
private String nombre;
private double notaMedia;
public Alumno(String n,double nm) {
nombre=n;
notaMedia=nm;
}
@Override
public int compareTo(Alumno otroAlumno) {
if (notaMedia<otroAlumno.notaMedia)
return -1;
else return 1;
}
@Override
public String toString() {
return String.format("%s notaMedia=%.3f",nombre, notaMedia);
}
}

View File

@@ -0,0 +1,43 @@
package iesthiar;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Ejercicio_B3v2 {
public static void main(String[] args) {
Scanner entrada=new Scanner(System.in);
System.out.print("Introduce el nombre del fichero a ordenar: ");
String fichero=entrada.nextLine();
System.out.print("Introduce el nombre del fichero de salida: ");
String ficheroSalida=entrada.nextLine();
entrada.close();
try (FileWriter fw=new FileWriter(new File(ficheroSalida));
BufferedWriter bfw=new BufferedWriter(fw)){
entrada=new Scanner(new File(fichero));
ArrayList<String> palabras=new ArrayList<>();
while (entrada.hasNextLine())
palabras.add(entrada.nextLine());
Collections.sort(palabras);
for(String p: palabras) {
bfw.write(p);
bfw.newLine();
}
System.out.println("Fichero ordenado");
}
catch (FileNotFoundException e) {
System.out.println("Error al leer el fichero");
}
catch (IOException e) {
System.out.println("Error al escribir el fichero");
}
}
}

View File

@@ -4,7 +4,11 @@ import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Ejercicio_B4 {
@@ -29,8 +33,9 @@ public class Ejercicio_B4 {
File fileApellidos = new File("target/classes/iesthiar/Documentos/usa_apellidos.txt");
// ArrayList con los datos de los ficheros de lectura
ArrayList<String> listaNombres = leerDatosFichero(fileNombres);
//ArrayList<String> listaNombres = leerDatosFichero(fileNombres);
ArrayList<String> listaApellidos = leerDatosFichero(fileApellidos);
List<String> listaNombres=Files.readAllLines(Paths.get("target/classes/iesthiar/Documentos/usa_nombres.txt"));
// Generamos el nombre y apellido aleatoriamente y lo escribimos en el fichero
try ( // FileWriter para escritura
@@ -56,7 +61,7 @@ public class Ejercicio_B4 {
// Devuelve un ArrayList con los datos leidos del fichero
public static ArrayList<String> leerDatosFichero(File f) throws FileNotFoundException {
try ( Scanner lector = new Scanner(f);){
try ( Scanner lector = new Scanner(f);){
ArrayList<String> lista = new ArrayList<>();
while (lector.hasNext()) {
lista.add(lector.nextLine());

View File

@@ -24,8 +24,8 @@ public class Ejercicio_B5 {
ArrayList<String> alDiccionario = new ArrayList<>();
// Lectura de diccionario.txt
File fileDiccionario = new File("Documentos/diccionario.txt");
Scanner reader = new Scanner(fileDiccionario);
//File fileDiccionario = new File("Documentos/diccionario.txt");
Scanner reader = new Scanner(Ejercicio_B5.class.getResourceAsStream("Documentos/diccionario.txt"));
// Recorremos el archivo y vamos añadiendo las palabras al ArrayList
while (reader.hasNext()) {
@@ -34,6 +34,7 @@ public class Ejercicio_B5 {
// Cerramos archivo
reader.close();
System.out.println(alDiccionario.size());
// Creamos dentro de la carpeta 'Diccionario' tantos archivos como letras del abecedario (A.txt, B.txt, C.txt,...)
for (int i = 65; i <= 90; i++) {

View File

@@ -16,8 +16,8 @@ public class Ejercicio_B6 {
String numeroBuscar = teclado.nextLine();
// Intentamos abrir el fichero 'pi-million.txt'
File fileNumeroPI = new File("Documentos/pi-million.txt");
Scanner lector = new Scanner(fileNumeroPI);
//File fileNumeroPI = new File("Documentos/pi-million.txt");
Scanner lector = new Scanner(Ejercicio_B6.class.getResourceAsStream("Documentos/pi-million.txt"));
//Cogemos todos los decimales del número PI del fichero
String decimalesPI = (lector.nextLine()).substring(2);
@@ -44,8 +44,8 @@ public class Ejercicio_B6 {
System.out.println("El número " + numeroBuscar + " no ha sido encontrado" );
}
} catch (FileNotFoundException e){
System.out.println("Error: El fichero no existe");
// } catch (FileNotFoundException e){
// System.out.println("Error: El fichero no existe");
}catch (Exception e) {
System.out.println("Error: " + e);
}

View File

@@ -0,0 +1,80 @@
package iesthiar;
/*
* Añadimos la dependencia en pom.xml para añadir el fichero Persona.jar
* <dependency>
<groupId>utilidades</groupId>
<artifactId>persona</artifactId>
<scope>system</scope>
<version>1.0</version>
<systemPath>${basedir}/Documentos/Persona.jar</systemPath>
</dependency>
*/
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import utilidades.Persona;
public class Ejercicio_B8 {
public static void main(String[] args) {
Map<String,Persona> personas=new HashMap<>();
try (Scanner lectura=new Scanner(new File("Documentos/datos_personas.csv"))){
while (lectura.hasNextLine()){
String linea=lectura.nextLine();
String[] elementos=linea.split(";");
if (elementos.length==4){
Persona p=new Persona(elementos[0],elementos[1],elementos[2],Integer.parseInt(elementos[3]));
personas.put(p.getDni(),p);
}
else System.err.println("Errór en lectura de elemento:"+linea);
}
System.out.println("Se han incorporado "+personas.size()+" personas");
} catch (FileNotFoundException e) {
System.out.println("Fichero no encontrado");
//throw new RuntimeException(e);
}
// Segunda parte. Datos de las personas
String respuesta="";
try (Scanner entrada=new Scanner(System.in)) {
while (!respuesta.toLowerCase().equals("fin")) {
System.out.println("Introduce un dni a mostrar (fin termina): ");
respuesta = entrada.nextLine();
if (!respuesta.equalsIgnoreCase("fin")){
Persona p=personas.get(respuesta);
if (p!=null)
p.imprime();
else
System.out.println("Ese DNI no se encuentra");
}
}
}
// Tercera parte. Salida de jubilados
try (BufferedWriter salida=new BufferedWriter(new FileWriter("Documentos/datos_jubilados.csv"))){
List<String> dnis= new ArrayList<>(personas.keySet());
Collections.sort(dnis);
for (String dni : dnis) {
Persona p=personas.get(dni);
if (p.esJubilado()) {
salida.write(p.getDni() + ";" + p.getNombre() + ";" + p.getApellidos() + ";" + p.getEdad());
salida.newLine();
}
}
System.out.println("Creación del fichero finalizada");
} catch (IOException e) {
System.out.println("Error al escribir el fichero de salida");
//throw new RuntimeException(e);
}
}
}

View File

@@ -0,0 +1,62 @@
package iesthiar;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import utilidades.Persona;
public class Ejercicio_B9 {
public static void main(String[] args) {
ArrayList<Persona> personas;
// Primera parte. Lectura objeto serializado
try (FileInputStream fis=new FileInputStream("Documentos/datos_personas.bin");
BufferedInputStream bis=new BufferedInputStream(fis);
ObjectInputStream ois=new ObjectInputStream(bis)
){
personas=(ArrayList<Persona>)ois.readObject();
System.out.println("Se han incorporado "+personas.size()+" personas");
// Segunda parte. Filtrado de los datos
List<Persona> veintes=personas.stream()
.filter(persona -> persona.getEdad()>=20 && persona.getEdad()<=29)
.toList();
// Versión clásica. Recorrido de la estructura
// List<Persona> veintes=new ArrayList<>();
// for (Persona persona : personas) {
// if (persona.getEdad()>=20 && persona.getEdad()<=29)
// veintes.add(persona);
// }
System.out.println("Tenemos "+veintes.size()+" veinteañeros");
// Tercera parte. Guardado de la estructura, serialización
try (FileOutputStream fos=new FileOutputStream("Documentos/datos_veintes.bin",false);
BufferedOutputStream bos=new BufferedOutputStream(fos);
ObjectOutputStream oos=new ObjectOutputStream(bos)){
oos.writeObject(veintes);
} catch (IOException e) {
throw new RuntimeException(e);
}
} catch (FileNotFoundException e) {
System.out.println("Fichero no encontrado");
//throw new RuntimeException(e);
} catch (IOException e) {
System.out.println("Error en la lectura del fichero");
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
System.out.println("Error en la lectura de los datos");
throw new RuntimeException(e);
}
}
}