├── .gitignore
├── README.md
├── Regex
└── davechild_regular-expressions.pdf
├── Soluciones
├── 01-FicherosTexto
│ ├── .gitignore
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── description.html
│ │ ├── encodings.xml
│ │ ├── misc.xml
│ │ ├── modules.xml
│ │ ├── project-template.xml
│ │ ├── uiDesigner.xml
│ │ └── vcs.xml
│ ├── 03-FicherosTexto.iml
│ └── src
│ │ └── es
│ │ └── joseluisgs
│ │ └── dam
│ │ ├── FicherosTexto.java
│ │ ├── Main.java
│ │ ├── controllers
│ │ └── PersonaController.java
│ │ └── model
│ │ └── Persona.java
├── 02-FicherosBinarios
│ ├── .gitignore
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── description.html
│ │ ├── encodings.xml
│ │ ├── misc.xml
│ │ ├── modules.xml
│ │ ├── project-template.xml
│ │ ├── uiDesigner.xml
│ │ └── vcs.xml
│ ├── 04-FicherosBinarios.iml
│ └── src
│ │ └── es
│ │ └── joseluisgs
│ │ └── dam
│ │ ├── FicherosBinarios.java
│ │ ├── Main.java
│ │ ├── controllers
│ │ └── PersonaController.java
│ │ ├── model
│ │ ├── Empleado.java
│ │ └── Persona.java
│ │ └── utils
│ │ └── Formatter.java
├── 03-FicherosAccesoAleatorio
│ ├── .gitignore
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── description.html
│ │ ├── encodings.xml
│ │ ├── misc.xml
│ │ ├── modules.xml
│ │ ├── project-template.xml
│ │ └── vcs.xml
│ ├── 05-FicherosAccesoAleatorio.iml
│ └── src
│ │ └── es
│ │ └── joseluisgs
│ │ └── dam
│ │ ├── EjemplosVarios.java
│ │ └── Main.java
├── 04-FicherosDirectorios
│ ├── .gitignore
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── description.html
│ │ ├── encodings.xml
│ │ ├── misc.xml
│ │ ├── modules.xml
│ │ ├── project-template.xml
│ │ ├── runConfigurations.xml
│ │ └── vcs.xml
│ ├── 06-FicherosDirectorios.iml
│ └── src
│ │ └── es
│ │ └── joseluisgs
│ │ └── dam
│ │ └── Main.java
├── 06-FicherosUtils
│ ├── .gitignore
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── description.html
│ │ ├── encodings.xml
│ │ ├── misc.xml
│ │ ├── modules.xml
│ │ ├── project-template.xml
│ │ ├── runConfigurations.xml
│ │ └── vcs.xml
│ ├── 08-FicherosUtils.iml
│ └── src
│ │ └── es
│ │ └── joseluisgs
│ │ └── dam
│ │ └── Main.java
├── 07-Json-Gson
│ ├── .gitignore
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── compiler.xml
│ │ ├── description.html
│ │ ├── encodings.xml
│ │ ├── jarRepositories.xml
│ │ ├── libraries
│ │ │ ├── Maven__com_google_code_gson_gson_2_9_0.xml
│ │ │ └── Maven__org_projectlombok_lombok_1_18_22.xml
│ │ ├── misc.xml
│ │ ├── modules.xml
│ │ └── project-template.xml
│ ├── Json-Gson.iml
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ └── java
│ │ └── es
│ │ └── joseluisgs
│ │ └── dam
│ │ ├── Main.java
│ │ └── model
│ │ ├── Menu.java
│ │ └── Producto.java
├── 08-ExpresionesRegulares
│ ├── .gitignore
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── description.html
│ │ ├── encodings.xml
│ │ ├── misc.xml
│ │ ├── modules.xml
│ │ ├── project-template.xml
│ │ ├── runConfigurations.xml
│ │ └── vcs.xml
│ ├── 11-ExpresionesRegulares.iml
│ └── src
│ │ └── es
│ │ └── joseluisgs
│ │ └── dam
│ │ ├── ExrpesionesRegulares.java
│ │ └── Main.java
├── 09-StringPattern
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── description.html
│ │ ├── encodings.xml
│ │ ├── misc.xml
│ │ ├── modules.xml
│ │ └── project-template.xml
│ ├── StringPattern.iml
│ └── src
│ │ └── es
│ │ └── joseluisgs
│ │ └── dam
│ │ └── Main.java
├── 10-MVC-Paises-FicherosTexto
│ ├── .gitignore
│ ├── SecuenciaPaises.iml
│ ├── data
│ │ └── paises.txt
│ └── src
│ │ └── es
│ │ └── joseluisgs
│ │ └── dam
│ │ ├── Main.java
│ │ ├── comparators
│ │ ├── PaisCodigoComparator.java
│ │ └── PaisNombreComparator.java
│ │ ├── controllers
│ │ ├── AcuerdoController.java
│ │ └── PaisController.java
│ │ ├── exceptions
│ │ └── PaisException.java
│ │ ├── models
│ │ ├── Acuerdo.java
│ │ ├── LineaAcuerdo.java
│ │ └── Pais.java
│ │ ├── repositories
│ │ ├── AcuerdoRepository.java
│ │ ├── CRUDRepository.java
│ │ ├── IAcuerdoRepository.java
│ │ ├── IPaisRepository.java
│ │ └── PaisRepository.java
│ │ ├── services
│ │ ├── IStorage.java
│ │ ├── IStoragePaises.java
│ │ └── StoragePaisesCSVFile.java
│ │ ├── utils
│ │ ├── Console.java
│ │ └── Formatter.java
│ │ └── views
│ │ └── PaisView.java
├── 12-MVC-Paises-FicherosJson
│ ├── .gitignore
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── compiler.xml
│ │ ├── description.html
│ │ ├── encodings.xml
│ │ ├── jarRepositories.xml
│ │ ├── libraries
│ │ │ └── Maven__com_google_code_gson_gson_2_9_0.xml
│ │ ├── misc.xml
│ │ ├── modules.xml
│ │ ├── project-template.xml
│ │ └── uiDesigner.xml
│ ├── SecuenciaPaises.iml
│ ├── data
│ │ └── paises.json
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ └── java
│ │ └── es
│ │ └── joseluisgs
│ │ └── dam
│ │ ├── Main.java
│ │ ├── comparators
│ │ ├── PaisCodigoComparator.java
│ │ └── PaisNombreComparator.java
│ │ ├── controllers
│ │ ├── AcuerdoController.java
│ │ └── PaisController.java
│ │ ├── exceptions
│ │ └── PaisException.java
│ │ ├── models
│ │ ├── Acuerdo.java
│ │ ├── LineaAcuerdo.java
│ │ └── Pais.java
│ │ ├── repositories
│ │ ├── AcuerdoRepository.java
│ │ ├── CRUDRepository.java
│ │ ├── IAcuerdoRepository.java
│ │ ├── IPaisRepository.java
│ │ └── PaisRepository.java
│ │ ├── services
│ │ ├── IStorage.java
│ │ ├── IStoragePaises.java
│ │ └── StoragePaisesJsonFile.java
│ │ ├── utils
│ │ ├── Console.java
│ │ └── Formatter.java
│ │ └── views
│ │ └── PaisView.java
└── 13-Pokedex
│ ├── .idea
│ ├── .gitignore
│ ├── compiler.xml
│ ├── description.html
│ ├── encodings.xml
│ ├── jarRepositories.xml
│ ├── libraries
│ │ └── Maven__com_google_code_gson_gson_2_9_0.xml
│ ├── misc.xml
│ ├── modules.xml
│ └── project-template.xml
│ ├── Pokedex.iml
│ ├── data
│ └── pokemon.json
│ ├── pom.xml
│ └── src
│ └── main
│ └── java
│ └── es
│ └── joseluisgs
│ └── dam
│ ├── Main.java
│ ├── controllers
│ └── PokemonController.java
│ └── models
│ ├── NextEvolution.java
│ ├── Pokedex.java
│ ├── Pokemon.java
│ └── PrevEvolution.java
└── UD08.pdf
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pptx
2 | .DS_Store
3 | /Ejercicios/*.docx
4 | upload.sh
5 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Programación - 08 Lectura y Escritura de Información Externa. Ficheros
2 |
3 | Tema 08 Lectura y Escritura de Información Externa. Ficheros. 1DAM. Curso 2021/2022.
4 |
5 | 
6 |
7 | ## Contenidos
8 | 1. Ficheros y Directorios.
9 | 2. Java Nio2.
10 | 3. Expresiones regulares.
11 | 4. JSON.
12 | 5. Localización.
13 |
14 |
15 | ## Recursos
16 | - Twitter: https://twitter.com/joseluisgonsan
17 | - GitHub: https://github.com/joseluisgs
18 | - Web: https://joseluisgs.github.io
19 | - Discord: https://discord.gg/uv7GcytM
20 | - Aula Virtual: https://aulavirtual33.educa.madrid.org/ies.luisvives.leganes/course/view.php?id=245
21 |
22 |
23 |
24 | ## Autor
25 |
26 | Codificado con :sparkling_heart: por [José Luis González Sánchez](https://twitter.com/joseluisgonsan)
27 |
28 | [](https://twitter.com/joseluisgonsan)
29 | [](https://github.com/joseluisgs)
30 |
31 | ### Contacto
32 |
33 | Cualquier cosa que necesites házmelo saber por si puedo ayudarte 💬.
34 |
35 |
36 |
37 |
39 |
40 |
41 |
43 |
44 |
45 |
47 |
48 |
49 |
51 |
52 |
--------------------------------------------------------------------------------
/Regex/davechild_regular-expressions.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-08-2021-2022/be39cbce5e9e73858b2c7802b70045b274150272/Regex/davechild_regular-expressions.pdf
--------------------------------------------------------------------------------
/Soluciones/01-FicherosTexto/.gitignore:
--------------------------------------------------------------------------------
1 | /out
2 | /prueba.txt
3 | /backup
4 | /data
--------------------------------------------------------------------------------
/Soluciones/01-FicherosTexto/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Datasource local storage ignored files
5 | /dataSources/
6 | /dataSources.local.xml
7 | # Editor-based HTTP Client requests
8 | /httpRequests/
9 |
--------------------------------------------------------------------------------
/Soluciones/01-FicherosTexto/.idea/description.html:
--------------------------------------------------------------------------------
1 | Simple Java application that includes a class with main() method
--------------------------------------------------------------------------------
/Soluciones/01-FicherosTexto/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Soluciones/01-FicherosTexto/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Soluciones/01-FicherosTexto/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Soluciones/01-FicherosTexto/.idea/project-template.xml:
--------------------------------------------------------------------------------
1 |
2 | IJ_BASE_PACKAGE
3 |
--------------------------------------------------------------------------------
/Soluciones/01-FicherosTexto/.idea/uiDesigner.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | -
6 |
7 |
8 | -
9 |
10 |
11 | -
12 |
13 |
14 | -
15 |
16 |
17 | -
18 |
19 |
20 |
21 |
22 |
23 | -
24 |
25 |
26 |
27 |
28 |
29 | -
30 |
31 |
32 |
33 |
34 |
35 | -
36 |
37 |
38 |
39 |
40 |
41 | -
42 |
43 |
44 |
45 |
46 | -
47 |
48 |
49 |
50 |
51 | -
52 |
53 |
54 |
55 |
56 | -
57 |
58 |
59 |
60 |
61 | -
62 |
63 |
64 |
65 |
66 | -
67 |
68 |
69 |
70 |
71 | -
72 |
73 |
74 | -
75 |
76 |
77 |
78 |
79 | -
80 |
81 |
82 |
83 |
84 | -
85 |
86 |
87 |
88 |
89 | -
90 |
91 |
92 |
93 |
94 | -
95 |
96 |
97 |
98 |
99 | -
100 |
101 |
102 | -
103 |
104 |
105 | -
106 |
107 |
108 | -
109 |
110 |
111 | -
112 |
113 |
114 |
115 |
116 | -
117 |
118 |
119 | -
120 |
121 |
122 |
123 |
124 |
--------------------------------------------------------------------------------
/Soluciones/01-FicherosTexto/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Soluciones/01-FicherosTexto/03-FicherosTexto.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Soluciones/01-FicherosTexto/src/es/joseluisgs/dam/FicherosTexto.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam;
2 |
3 | import java.io.*;
4 |
5 | public class FicherosTexto {
6 | public static void testEscribirFicheroTexto() {
7 | File fichero = null;
8 | PrintWriter f = null;
9 | try
10 | {
11 |
12 | fichero = new File("prueba.txt");
13 | System.out.println("Escribiendo en el fichero:"+fichero.getAbsolutePath());
14 |
15 |
16 |
17 |
18 | // Creamos el buffer y le asociamos el fichero
19 | // Usamos PrintWriter y no BufferedWriter porque tiene mejores metodos
20 | // Pero podríamos usar BufferedWriter y usar \n
21 | // al poner FileWriter -> true no sobrescribimos
22 | f = new PrintWriter(new FileWriter(fichero,true));
23 |
24 | // Escribimos diez lineas
25 | for (int i = 0; i < 10; i++){
26 | f.println("Linea:"+i); //-->>
27 | }
28 | // vamos a escribir la propia ruta del fichero en el fichero
29 | // usamos la clase file
30 |
31 | f.println(fichero.getAbsolutePath());
32 |
33 | } catch (IOException e) {
34 | e.printStackTrace();
35 | } finally {
36 | try {
37 | // Nuevamente aprovechamos el finally para
38 | // asegurarnos que se cierra el fichero.
39 | if (f != null)
40 | f.close();
41 | } catch (Exception e2) {
42 | e2.printStackTrace();
43 | }
44 | }
45 | }
46 |
47 | public static void testLeerFicheroTexto() {
48 | File fichero = null;
49 | BufferedReader f = null;
50 | try
51 | {
52 |
53 | fichero = new File("prueba.txt");
54 | System.out.println("Leyendo del fichero:"+fichero.getAbsolutePath());
55 |
56 | // Creamos el buffer y le asociamos el fichero
57 | f = new BufferedReader(new FileReader(fichero));
58 |
59 | //leemos hasta el final del fichero linea a línea
60 | String linea = f.readLine();
61 | while(linea!=null){
62 | System.out.println(linea); // --->>
63 | linea = f.readLine();
64 | }
65 |
66 | //Otra forma más corta
67 | //String linea;
68 | //while((linea=f.readLine())!=null){
69 | //System.out.println(linea);
70 | //}
71 | } catch (IOException e) {
72 | e.printStackTrace();
73 | } finally {
74 | try {
75 | // Nuevamente aprovechamos el finally para
76 | // asegurarnos que se cierra el fichero.
77 | if (f != null)
78 | f.close();
79 | } catch (Exception e2) {
80 | e2.printStackTrace();
81 | }
82 | }
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/Soluciones/01-FicherosTexto/src/es/joseluisgs/dam/Main.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam;
2 |
3 | import es.joseluisgs.dam.controllers.PersonaController;
4 | import es.joseluisgs.dam.model.Persona;
5 |
6 | import java.util.List;
7 |
8 | public class Main {
9 |
10 | public static void main(String[] args) {
11 | // FicherosTexto.testEscribirFicheroTexto();
12 | // FicherosTexto.testLeerFicheroTexto();
13 | PersonaController pc = new PersonaController();
14 | pc.getDir();
15 | List personas = List.of(
16 | new Persona("Juan", "juan@juan.es"),
17 | new Persona("Pepe", "pepe@pepe.es"),
18 | new Persona("Luis", "luis@luis.es")
19 | );
20 | pc.savePersonas(personas, false);
21 | List res = pc.readPersonas();
22 | for (Persona p : res) {
23 | System.out.println(p);
24 | }
25 |
26 | pc.backup();
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Soluciones/01-FicherosTexto/src/es/joseluisgs/dam/controllers/PersonaController.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam.controllers;
2 |
3 | import es.joseluisgs.dam.model.Persona;
4 |
5 | import java.io.*;
6 | import java.nio.file.Files;
7 | import java.nio.file.Path;
8 | import java.nio.file.Paths;
9 | import java.time.LocalDateTime;
10 | import java.util.ArrayList;
11 | import java.util.List;
12 |
13 | public class PersonaController {
14 | private Path currentRelativePath = Paths.get("");
15 | private String ruta = currentRelativePath.toAbsolutePath().toString();
16 | private final String dir = ruta + File.separator + "data";
17 | private final String backup = ruta + File.separator + "backup";
18 | private final String personasFile = dir + File.separator + "personas.txt";
19 |
20 | public PersonaController() {
21 | init();
22 | }
23 |
24 | private void init() {
25 | File directory = new File(this.dir);
26 | if (!directory.exists()) {
27 | directory.mkdir();
28 | }
29 |
30 | Path path = Paths.get(dir);
31 | if (!Files.exists(path)) {
32 | try {
33 | Files.createDirectories(path);
34 | } catch (IOException e) {
35 | System.out.println("Error: " + e.getMessage());
36 | }
37 | }
38 | }
39 |
40 | public void getDir() {
41 | System.out.println(dir);
42 | }
43 |
44 | public void savePersonas(List personas, boolean append) {
45 | File fichero = null;
46 | PrintWriter f = null;
47 | try {
48 | fichero = new File(personasFile);
49 | f = new PrintWriter(new FileWriter(personasFile,append));
50 |
51 | for (Persona p : personas) {
52 | f.println(p.toFile());
53 | }
54 |
55 | } catch (Exception e) {
56 | System.out.println("Error: " + e.getMessage());
57 | } finally {
58 | if (f != null) {
59 | f.close();
60 | }
61 | }
62 | }
63 |
64 | public List readPersonas() {
65 | File fichero = null;
66 | BufferedReader f = null;
67 | List personas = new ArrayList<>();
68 | try {
69 | fichero = new File(personasFile);
70 | f = new BufferedReader(new FileReader(fichero));
71 |
72 | String linea;
73 | while ((linea = f.readLine()) != null) {
74 | personas.add(getPersona(linea));
75 | }
76 |
77 | } catch (Exception e) {
78 | System.out.println("Error: " + e.getMessage());
79 | } finally {
80 | if (f != null) {
81 | try {
82 | f.close();
83 | } catch (IOException e) {
84 | System.out.println("Error: " + e.getMessage());
85 | }
86 | }
87 | }
88 | return personas;
89 | }
90 |
91 | private Persona getPersona(String linea) {
92 | String[] campos = linea.split(";");
93 | var id = Integer.parseInt(campos[0]);
94 | var nombre = campos[1];
95 | var email = campos[2];
96 | var createdAt = LocalDateTime.parse(campos[3]);
97 | var p = new Persona(id, nombre, email, createdAt);
98 | // System.out.println(p);
99 | return p;
100 | }
101 |
102 |
103 | public void backup() {
104 | Path pathOrigen = Paths.get(personasFile);
105 | Path pathFinal = Paths.get(backup + File.separator + "personas.bak");
106 | if (!Files.exists(Paths.get(backup))) {
107 | try {
108 | Files.createDirectories(Paths.get(backup));
109 | Files.copy(pathOrigen, pathFinal);
110 | } catch (IOException e) {
111 | System.out.println("Error: " + e.getMessage());
112 | }
113 | }
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/Soluciones/01-FicherosTexto/src/es/joseluisgs/dam/model/Persona.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam.model;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | public class Persona {
6 | private int id;
7 | private String nombre;
8 | private String email;
9 | private LocalDateTime createdAt;
10 |
11 | private static int contador = 0;
12 |
13 | public Persona(String nombre, String email) {
14 | this.id = ++contador;
15 | this.nombre = nombre;
16 | this.email = email;
17 | this.createdAt = LocalDateTime.now();
18 | }
19 |
20 | public Persona(int id, String nombre, String email, LocalDateTime createdAt) {
21 | this.id = id;
22 | this.nombre = nombre;
23 | this.email = email;
24 | this.createdAt = createdAt;
25 | }
26 |
27 | @Override
28 | public String toString() {
29 | return "Persona{" + "id=" + id + ", nombre=" + nombre + ", email=" + email + ", createdAt=" + createdAt + '}';
30 | }
31 |
32 | public String toFile() {
33 | return id + ";" + nombre + ";" + email + ";" + createdAt;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/Soluciones/02-FicherosBinarios/.gitignore:
--------------------------------------------------------------------------------
1 | /out
2 | /empleados
3 | /backup
4 | /data
--------------------------------------------------------------------------------
/Soluciones/02-FicherosBinarios/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Datasource local storage ignored files
5 | /dataSources/
6 | /dataSources.local.xml
7 | # Editor-based HTTP Client requests
8 | /httpRequests/
9 |
--------------------------------------------------------------------------------
/Soluciones/02-FicherosBinarios/.idea/description.html:
--------------------------------------------------------------------------------
1 | Simple Java application that includes a class with main() method
--------------------------------------------------------------------------------
/Soluciones/02-FicherosBinarios/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Soluciones/02-FicherosBinarios/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Soluciones/02-FicherosBinarios/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Soluciones/02-FicherosBinarios/.idea/project-template.xml:
--------------------------------------------------------------------------------
1 |
2 | IJ_BASE_PACKAGE
3 |
--------------------------------------------------------------------------------
/Soluciones/02-FicherosBinarios/.idea/uiDesigner.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | -
6 |
7 |
8 | -
9 |
10 |
11 | -
12 |
13 |
14 | -
15 |
16 |
17 | -
18 |
19 |
20 |
21 |
22 |
23 | -
24 |
25 |
26 |
27 |
28 |
29 | -
30 |
31 |
32 |
33 |
34 |
35 | -
36 |
37 |
38 |
39 |
40 |
41 | -
42 |
43 |
44 |
45 |
46 | -
47 |
48 |
49 |
50 |
51 | -
52 |
53 |
54 |
55 |
56 | -
57 |
58 |
59 |
60 |
61 | -
62 |
63 |
64 |
65 |
66 | -
67 |
68 |
69 |
70 |
71 | -
72 |
73 |
74 | -
75 |
76 |
77 |
78 |
79 | -
80 |
81 |
82 |
83 |
84 | -
85 |
86 |
87 |
88 |
89 | -
90 |
91 |
92 |
93 |
94 | -
95 |
96 |
97 |
98 |
99 | -
100 |
101 |
102 | -
103 |
104 |
105 | -
106 |
107 |
108 | -
109 |
110 |
111 | -
112 |
113 |
114 |
115 |
116 | -
117 |
118 |
119 | -
120 |
121 |
122 |
123 |
124 |
--------------------------------------------------------------------------------
/Soluciones/02-FicherosBinarios/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Soluciones/02-FicherosBinarios/04-FicherosBinarios.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Soluciones/02-FicherosBinarios/src/es/joseluisgs/dam/FicherosBinarios.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam;
2 |
3 | import es.joseluisgs.dam.model.Empleado;
4 |
5 | import java.io.*;
6 | import java.util.Stack;
7 |
8 | public class FicherosBinarios {
9 | public static void testEscribirFicheroBinario() {
10 |
11 | // Rutas de ficheros
12 | ObjectOutputStream f = null;
13 | File fichero = null;
14 |
15 | Empleado empleado1=new Empleado("Fernando", "Ureña", 23, 800);
16 | Empleado empleado2=new Empleado("Antonio", "Lopez", 35, 1000);
17 |
18 | Stack pila= new Stack();
19 |
20 | pila.add(empleado1);
21 | pila.add(empleado2);
22 |
23 | try{
24 | fichero = new File("empleados");
25 | f = new ObjectOutputStream(new FileOutputStream(fichero));
26 | //Escribimos en un fichero
27 | // podríamos escribir un array list o arbol si todos son
28 | // serializables
29 | System.out.println("Escribiendo objetos binarios en:"+fichero.getAbsolutePath());
30 | f.writeObject(empleado1);
31 | f.writeObject(empleado2);
32 | f.writeObject(pila);
33 | System.out.println("Escritos");
34 | }catch(IOException e){
35 | //e.printStackTrace();
36 | } finally {
37 | try {
38 | // Nuevamente aprovechamos el finally para
39 | // asegurarnos que se cierra el fichero.
40 | if (f != null)
41 | f.close();
42 | System.out.println("Fichero cerrado");
43 | } catch (Exception e2) {
44 | e2.printStackTrace();
45 | }
46 | }
47 | }
48 |
49 | public static void testLeerFicheroBinario(){
50 | // Rutas de ficheros
51 | ObjectInputStream f = null;
52 | File fichero = null;
53 |
54 | try{
55 | fichero = new File("empleados");
56 | f = new ObjectInputStream(new FileInputStream(fichero));
57 | //Escribimos en un fichero
58 | // podríamos escribir un array list o arbol si todos son
59 | // serializables
60 | System.out.println("Leyendo objetos binarios en:"+fichero.getAbsolutePath());
61 |
62 | // Se lee el primer objeto
63 | Empleado emp1 = (Empleado)f.readObject();
64 | System.out.println(emp1.toString());
65 | Empleado emp2 = (Empleado)f.readObject();
66 | System.out.println(emp2.toString());
67 | Stack pila= (Stack) f.readObject();
68 | System.out.println(pila.pop().toString());
69 | System.out.println(pila.pop().toString());
70 | System.out.println(pila.empty());
71 | /*
72 | while(aux!=null){
73 | if (aux instanceof Empleado){
74 | System.out.println(aux.toString());
75 | }
76 | // Leemos si hay mas objetos
77 | aux=(Empleado)f.readObject();
78 |
79 | }
80 | */
81 | }catch(IOException e){
82 | //e.printStackTrace();
83 | } catch (ClassNotFoundException ex) {
84 | System.err.println("Clases Incompatibles");
85 | } finally {
86 | try {
87 | // Nuevamente aprovechamos el finally para
88 | // asegurarnos que se cierra el fichero.
89 | if (f != null)
90 | f.close();
91 | System.out.println("Fichero cerrado");
92 | } catch (Exception e2) {
93 | e2.printStackTrace();
94 | }
95 | }
96 | }
97 |
98 | }
99 |
--------------------------------------------------------------------------------
/Soluciones/02-FicherosBinarios/src/es/joseluisgs/dam/Main.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam;
2 |
3 | import es.joseluisgs.dam.controllers.PersonaController;
4 | import es.joseluisgs.dam.model.Persona;
5 |
6 | import java.util.List;
7 |
8 | public class Main {
9 |
10 | public static void main(String[] args) {
11 | // FicherosBinarios.testEscribirFicheroBinario();
12 | // FicherosBinarios.testLeerFicheroBinario();
13 | PersonaController pc = new PersonaController();
14 | pc.getDir();
15 | List personas = List.of(
16 | new Persona("Juan", "juan@juan.es"),
17 | new Persona("Pepe", "pepe@pepe.es"),
18 | new Persona("Luis", "luis@luis.es")
19 | );
20 | pc.savePersonas1By1(personas, false);
21 | List res = pc.readPersonas1By1();
22 | for (Persona p : res) {
23 | System.out.println(p);
24 | }
25 |
26 | pc.savePersonasList(personas, false);
27 | List res2 = pc.readPersonasList();
28 | for (Persona p : res2) {
29 | System.out.println(p);
30 | }
31 |
32 | pc.backup();
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Soluciones/02-FicherosBinarios/src/es/joseluisgs/dam/controllers/PersonaController.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam.controllers;
2 |
3 | import es.joseluisgs.dam.model.Persona;
4 |
5 | import java.io.*;
6 | import java.nio.file.Files;
7 | import java.nio.file.Path;
8 | import java.nio.file.Paths;
9 | import java.time.LocalDateTime;
10 | import java.util.ArrayList;
11 | import java.util.List;
12 |
13 | public class PersonaController {
14 | private Path currentRelativePath = Paths.get("");
15 | private String ruta = currentRelativePath.toAbsolutePath().toString();
16 | private final String dir = ruta + File.separator + "data";
17 | private final String backup = ruta + File.separator + "backup";
18 | private final String personasFile = dir + File.separator + "personas.dat";
19 |
20 | public PersonaController() {
21 | init();
22 | }
23 |
24 | private void init() {
25 | File directory = new File(this.dir);
26 | if (!directory.exists()) {
27 | directory.mkdir();
28 | }
29 |
30 | Path path = Paths.get(dir);
31 | if (!Files.exists(path)) {
32 | try {
33 | Files.createDirectories(path);
34 | } catch (IOException e) {
35 | System.out.println("Error: " + e.getMessage());
36 | }
37 | }
38 | }
39 |
40 | public void getDir() {
41 | System.out.println(dir);
42 | }
43 |
44 | public void savePersonas1By1(List personas, boolean append) {
45 | File fichero = null;
46 | ObjectOutputStream f = null;
47 | try {
48 | fichero = new File(personasFile);
49 | f = new ObjectOutputStream(new FileOutputStream(fichero, append));
50 |
51 | for (Persona p : personas) {
52 | f.writeObject(p);
53 | }
54 |
55 | } catch (Exception e) {
56 | System.out.println("Error Write: " + e.getMessage());
57 | } finally {
58 | if (f != null) {
59 | try {
60 | f.close();
61 | } catch (IOException e) {
62 | System.out.println("Error Close Write: " + e.getMessage());
63 | }
64 | }
65 | }
66 | }
67 |
68 | public List readPersonas1By1() {
69 | File fichero = null;
70 | ObjectInputStream f = null;
71 | List personas = new ArrayList<>();
72 | try {
73 | fichero = new File(personasFile);
74 | f = new ObjectInputStream(new FileInputStream(fichero));
75 |
76 | Persona persona;
77 | while ((persona = (Persona) f.readObject()) != null) {
78 | personas.add(persona);
79 | }
80 |
81 | } catch (ClassNotFoundException e) {
82 | System.out.println("Error Read: " + e.getMessage());
83 | } catch (EOFException e) {
84 | // System.out.println("Fin de fichero");
85 | } catch (IOException e) {
86 | e.printStackTrace();
87 | } finally {
88 | if (f != null) {
89 | try {
90 | f.close();
91 | } catch (IOException e) {
92 | System.out.println("Error Close Read: " + e.getMessage());
93 | }
94 | }
95 | }
96 | return personas;
97 | }
98 |
99 | public void backup() {
100 | Path pathOrigen = Paths.get(personasFile);
101 | Path pathFinal = Paths.get(backup + File.separator + "personas.bak");
102 | if (!Files.exists(Paths.get(backup))) {
103 | try {
104 | Files.createDirectories(Paths.get(backup));
105 | Files.copy(pathOrigen, pathFinal);
106 | } catch (IOException e) {
107 | System.out.println("Error: " + e.getMessage());
108 | }
109 | }
110 | }
111 |
112 | public void savePersonasList(List personas, boolean append) {
113 | File fichero = null;
114 | ObjectOutputStream f = null;
115 | try {
116 | fichero = new File(personasFile);
117 | f = new ObjectOutputStream(new FileOutputStream(fichero, append));
118 |
119 | f.writeObject(personas);
120 |
121 | } catch (Exception e) {
122 | System.out.println("Error Write: " + e.getMessage());
123 | } finally {
124 | if (f != null) {
125 | try {
126 | f.close();
127 | } catch (IOException e) {
128 | System.out.println("Error Close Write: " + e.getMessage());
129 | }
130 | }
131 | }
132 | }
133 |
134 | public List readPersonasList() {
135 | File fichero = null;
136 | ObjectInputStream f = null;
137 | List personas = new ArrayList<>();
138 | try {
139 | fichero = new File(personasFile);
140 | f = new ObjectInputStream(new FileInputStream(fichero));
141 |
142 | personas = (List) f.readObject();
143 |
144 | } catch (ClassNotFoundException | IOException e) {
145 | System.out.println("Error Read: " + e.getMessage());
146 | } finally {
147 | if (f != null) {
148 | try {
149 | f.close();
150 | } catch (IOException e) {
151 | System.out.println("Error Close Read: " + e.getMessage());
152 | }
153 | }
154 | }
155 | return personas;
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/Soluciones/02-FicherosBinarios/src/es/joseluisgs/dam/model/Empleado.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam.model;
2 |
3 | import java.io.Serializable;
4 | import java.util.Objects;
5 |
6 | /**
7 | *
8 | * @author joseluisgs
9 | */
10 | public class Empleado implements Serializable, Comparable{
11 |
12 | private static final long serialVersionUID = -2873344211410398459L;
13 |
14 | //Constantes
15 | /**
16 | * Constante SALARIO_DEF
17 | */
18 | protected final static double SALARIO_DEF=600;
19 |
20 | //Atributos
21 |
22 | /**
23 | * Nombre del empleado
24 | */
25 | protected String nombre;
26 | /**
27 | * Apellido del empleado
28 | */
29 | protected String apellido;
30 | /**
31 | * Edad del empleado
32 | */
33 | protected int edad;
34 | /**
35 | * Salario del empleado
36 | */
37 | protected double salario;
38 |
39 | //Metodos publicos
40 |
41 | /**
42 | * Devuelve el nombre del empleado
43 | * @return nombre del empleado
44 | */
45 | public String getNombre() {
46 | return nombre;
47 | }
48 |
49 | /**
50 | * Modifica el nombre de un empleado
51 | * @param nombre
52 | */
53 | public void setNombre(String nombre) {
54 | this.nombre = nombre;
55 | }
56 |
57 | /**
58 | * Devuelve la edad de un empleado
59 | * @return edad del empleado
60 | */
61 | public int getEdad() {
62 | return edad;
63 | }
64 |
65 | /**
66 | * Modifica la edad de un empleado
67 | * @param edad
68 | */
69 | public void setEdad(int edad) {
70 | this.edad = edad;
71 | }
72 |
73 | /**
74 | * Devuelve el salarioBase
75 | * @return salarioBse
76 | */
77 | public double getSalario() {
78 | return salario;
79 | }
80 |
81 | /**
82 | * Modifica el salarioBase de los empleados
83 | * @param salarioBase
84 | */
85 | public void setSalario(double salario) {
86 | this.salario = salario;
87 | }
88 |
89 | public boolean plus (double sueldoPlus){
90 |
91 | boolean aumento=false;
92 | if (edad>40){
93 | salario+=sueldoPlus;
94 | aumento=true;
95 | }
96 | return aumento;
97 | }
98 |
99 | public boolean equals (Empleado a){
100 |
101 | if(a.getNombre().equals(nombre) && a.getApellido().equals(apellido)){
102 | return true;
103 | }else{
104 | return false;
105 | }
106 | }
107 |
108 | @Override
109 | public int compareTo(Empleado a){
110 | int estado=-1;
111 | if(this.edad==a.getEdad()){
112 | //Los objetos son iguales
113 | estado=0;
114 | }else if(this.edad>a.getEdad()){
115 | //El objeto 1 es mayor que la pasada por parametro
116 | estado=1;
117 | }
118 | return estado;
119 |
120 | }
121 | @Override
122 | public String toString (){
123 | String mensaje="El empleado se llama "+nombre+" "+apellido+" con "+edad+" años " +
124 | "y un salario de "+salario;
125 | return mensaje;
126 | }
127 | public String getApellido() {
128 | return apellido;
129 | }
130 |
131 | //Constructores
132 | /**
133 | * Constructor por defecto
134 | */
135 | public Empleado(){
136 | this ("", "", 0, SALARIO_DEF);
137 | }
138 |
139 | /**
140 | * Constructor con 2 parametros
141 | * @param nombre nombre del empleado
142 | * @param apellido nombre del empleado
143 | */
144 | public Empleado(String nombre, String apellido){
145 | this (nombre, apellido, 0, SALARIO_DEF);
146 | }
147 |
148 |
149 | /**
150 | * Constructor con 3 parametros
151 | * @param nombre nombre del empleado
152 | * @param apellido nombre del empleado
153 | * @param edad edad del empleado
154 | */
155 | public Empleado (String nombre, String apellido, int edad){
156 | this (nombre, apellido, edad, SALARIO_DEF);
157 | }
158 | /**
159 | * Constructor con 4 parametros
160 | * @param nombre nombre del empleado
161 | * @param apellido nombre del empleado
162 | * @param edad edad del empleado
163 | * @param salario salario del empleado
164 | */
165 | public Empleado(String nombre, String apellido, int edad, double salario){
166 | this.nombre=nombre;
167 | this.apellido=apellido;
168 | this.edad=edad;
169 | this.salario=salario;
170 | }
171 |
172 |
173 |
174 | @Override
175 | public boolean equals(Object obj) {
176 | if (this == obj) {
177 | return true;
178 | }
179 | if (obj == null) {
180 | return false;
181 | }
182 | if (getClass() != obj.getClass()) {
183 | return false;
184 | }
185 | final Empleado other = (Empleado) obj;
186 | if (this.edad != other.edad) {
187 | return false;
188 | }
189 | if (Double.doubleToLongBits(this.salario) != Double.doubleToLongBits(other.salario)) {
190 | return false;
191 | }
192 | if (!Objects.equals(this.nombre, other.nombre)) {
193 | return false;
194 | }
195 | if (!Objects.equals(this.apellido, other.apellido)) {
196 | return false;
197 | }
198 | return true;
199 | }
200 |
201 | @Override
202 | public int hashCode() {
203 | int hash = 7;
204 | hash = 29 * hash + Objects.hashCode(this.nombre);
205 | hash = 29 * hash + Objects.hashCode(this.apellido);
206 | hash = 29 * hash + this.edad;
207 | hash = 29 * hash + (int) (Double.doubleToLongBits(this.salario) ^ (Double.doubleToLongBits(this.salario) >>> 32));
208 | return hash;
209 | }
210 |
211 | }
212 |
--------------------------------------------------------------------------------
/Soluciones/02-FicherosBinarios/src/es/joseluisgs/dam/model/Persona.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam.model;
2 |
3 | import es.joseluisgs.dam.utils.Formatter;
4 |
5 | import java.io.Serializable;
6 | import java.time.LocalDateTime;
7 |
8 | public class Persona implements Serializable {
9 | private static final long serialVersionUID = -87908723585899098L;
10 | private int id;
11 | private String nombre;
12 | private String email;
13 | private LocalDateTime createdAt;
14 | private Double salario;
15 |
16 | private static int contador = 0;
17 |
18 | public Persona(String nombre, String email) {
19 | this.id = ++contador;
20 | this.nombre = nombre;
21 | this.email = email;
22 | this.createdAt = LocalDateTime.now();
23 | this.salario = Math.random() * 100000;
24 | }
25 |
26 | public Persona(int id, String nombre, String email, LocalDateTime createdAt) {
27 | this.id = id;
28 | this.nombre = nombre;
29 | this.email = email;
30 | this.createdAt = createdAt;
31 | }
32 |
33 | @Override
34 | public String toString() {
35 | return "Persona{" + "id=" + id + ", nombre=" + nombre + ", email=" + email + ", createdAt=" + Formatter.dateParser(createdAt) + ", salario=" + Formatter.moneyParser(salario) + '}';
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Soluciones/02-FicherosBinarios/src/es/joseluisgs/dam/utils/Formatter.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam.utils;
2 |
3 | import java.text.NumberFormat;
4 | import java.time.LocalDateTime;
5 | import java.time.format.DateTimeFormatter;
6 | import java.time.format.FormatStyle;
7 | import java.util.Locale;
8 |
9 | public class Formatter {
10 |
11 | public static String dateParser(LocalDateTime date) {
12 | final Locale locale = new Locale("es", "ES");
13 | // private String pattern = "dd/MM/yyyy";
14 | return date.format(DateTimeFormatter
15 | .ofLocalizedDate(FormatStyle.FULL).withLocale(locale));
16 | }
17 |
18 | public static String moneyParser(Double money) {
19 | final Locale locale = new Locale("es", "ES");
20 | return NumberFormat.getCurrencyInstance(locale).format(money);
21 | }
22 |
23 | public static String doubleParser(Double number) {
24 | final Locale locale = new Locale("es", "ES");
25 | return NumberFormat.getInstance(locale).format(number);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Soluciones/03-FicherosAccesoAleatorio/.gitignore:
--------------------------------------------------------------------------------
1 | /out
2 | /enteros.dat
3 | /texto.txt
--------------------------------------------------------------------------------
/Soluciones/03-FicherosAccesoAleatorio/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Datasource local storage ignored files
5 | /dataSources/
6 | /dataSources.local.xml
7 | # Editor-based HTTP Client requests
8 | /httpRequests/
9 |
--------------------------------------------------------------------------------
/Soluciones/03-FicherosAccesoAleatorio/.idea/description.html:
--------------------------------------------------------------------------------
1 | Simple Java application that includes a class with main() method
--------------------------------------------------------------------------------
/Soluciones/03-FicherosAccesoAleatorio/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Soluciones/03-FicherosAccesoAleatorio/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Soluciones/03-FicherosAccesoAleatorio/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Soluciones/03-FicherosAccesoAleatorio/.idea/project-template.xml:
--------------------------------------------------------------------------------
1 |
2 | IJ_BASE_PACKAGE
3 |
--------------------------------------------------------------------------------
/Soluciones/03-FicherosAccesoAleatorio/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Soluciones/03-FicherosAccesoAleatorio/05-FicherosAccesoAleatorio.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Soluciones/03-FicherosAccesoAleatorio/src/es/joseluisgs/dam/EjemplosVarios.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam;
2 |
3 | import java.io.EOFException;
4 | import java.io.FileNotFoundException;
5 | import java.io.IOException;
6 | import java.io.RandomAccessFile;
7 | import java.util.Scanner;
8 |
9 | public class EjemplosVarios {
10 | /* Pide un número entero por teclado y lo añade al final de un fichero binario enteros.dat que contiene números enteros.
11 | El programa utiliza un método mostrarFichero() que se llama dos veces. La primera muestra el contenido del fichero antes
12 | de añadir el nuevo número y la segunda llamada muestra el fichero después de añadirlo.*/
13 | public static void escribirEntero() {
14 | Scanner sc = new Scanner(System.in);
15 | RandomAccessFile fichero = null;
16 | int numero;
17 | try {
18 | //se abre el fichero para lectura y escritura
19 | fichero = new RandomAccessFile("enteros.dat", "rw");
20 | mostrarFichero(); //muestra el contenido original del fichero
21 | System.out.print("Introduce un número entero para añadir al final del fichero: ");
22 | numero = sc.nextInt(); //se lee el entero a añadir en el fichero
23 | fichero.seek(fichero.length()); //nos situamos al final del fichero
24 | fichero.writeInt(numero); //se escribe el entero
25 | mostrarFichero();//muestra el contenido del fichero después de añadir el número
26 |
27 | } catch (FileNotFoundException ex) {
28 | System.out.println(ex.getMessage());
29 | } catch (IOException ex) {
30 | System.out.println(ex.getMessage());
31 | } finally {
32 | try {
33 | if (fichero != null) {
34 | fichero.close();
35 | }
36 | } catch (IOException e) {
37 | System.out.println(e.getMessage());
38 | }
39 | }
40 | }
41 |
42 |
43 | public static void mostrarFichero() {
44 | RandomAccessFile fichero = null;
45 | try {
46 | fichero = new RandomAccessFile("enteros.dat", "r");
47 | int n;
48 | try {
49 | fichero.seek(0); //nos situamos al principio
50 | while (true) {
51 | n = fichero.readInt(); //se lee un entero del fichero
52 | System.out.println(n); //se muestra en pantalla
53 |
54 | }
55 | } catch (EOFException e) {
56 | System.out.println("Fin de fichero");
57 | } catch (IOException ex) {
58 | System.out.println(ex.getMessage());
59 | }
60 | } catch (FileNotFoundException e) {
61 | e.printStackTrace();
62 | } finally {
63 | try {
64 | if (fichero != null) {
65 | fichero.close();
66 | }
67 | } catch (IOException e) {
68 | System.out.println(e.getMessage());
69 | }
70 | }
71 | }
72 |
73 | /*Modifica un entero dentro del fichero enteros.dat con acceso aleatorio.
74 | Para ello se pide la posición que ocupa el entero a modificar dentro del fichero,
75 | a continuación se lee y muestra el valor actual, se pide el nuevo valor y finalmente se escribe el nuevo valor
76 | en la posición indicada, modificando de esta forma el valor antiguo por el nuevo.*/
77 | public static void modificarEntero() {
78 | Scanner sc = new Scanner(System.in);
79 | RandomAccessFile fichero = null;
80 | int pos, numero;
81 | long size;
82 | try {
83 | fichero = new RandomAccessFile("enteros.dat", "rw");
84 |
85 | //calcular cuántos enteros tiene el fichero
86 | size = fichero.length();
87 | size = size / 4;
88 | System.out.println("El fichero tiene " + size + " enteros");
89 |
90 | //Modificar el entero que se encuentra en una posición determinada
91 | do {
92 | System.out.println("Introduce una posición (>=1 y <= " + size + "): ");
93 | pos = sc.nextInt();
94 | } while (pos < 1 || pos > size);
95 |
96 | pos--; //la posición 1 realmente es la 0
97 |
98 | //nos situamos en la posición (byte de inicio) del entero a modificar
99 | //en Java un entero ocupa 4 bytes
100 | fichero.seek(pos * 4);
101 |
102 | //leemos y mostramos el valor actual
103 | System.out.println("Valor actual: " + fichero.readInt());
104 |
105 | //pedimos que se introduzca el nuevo valor
106 | System.out.println("Introduce nuevo valor: ");
107 | numero = sc.nextInt();
108 |
109 | //nos situamos de nuevo en la posición del entero a modificar
110 | //esto es necesario porque después de la lectura que hemos realizado para mostrar
111 | //el valor el puntero de lectura/escritura ha avanzado al siguiente entero del fichero.
112 | //si no hacemos esto escribiremos sobre el siguiente entero
113 | fichero.seek(pos * 4);
114 |
115 | //escribimos el entero
116 | fichero.writeInt(numero);
117 |
118 | } catch (FileNotFoundException ex) {
119 | System.out.println(ex.getMessage());
120 | } catch (IOException ex) {
121 | System.out.println(ex.getMessage());
122 | } finally {
123 | try {
124 | if (fichero != null) {
125 | fichero.close();
126 | }
127 | } catch (IOException e) {
128 | System.out.println(e.getMessage());
129 | }
130 | }
131 | }
132 | /* Ejemplo de uso de un fichero de caracteres con acceso aleatorio.
133 | Se pide por teclado una palabra, la busca el fichero de texto texto.txt y la modifica escribiéndola en mayúsculas
134 | cada vez que aparece en el fichero.Para hacer el cambio de la palabra por su equivalente en mayúsculas, el programa
135 | lee el fichero por líneas. Para cada línea leída se comprueba si contiene la palabra buscada y si es así se modifica
136 | y se sobrescribe la línea completa modificada. */
137 | public static void palabras() {
138 | Scanner sc = new Scanner(System.in);
139 | RandomAccessFile fichero = null;
140 | String palabra, cadena;
141 | StringBuilder auxBuilder;
142 | long pos = 0;
143 | int indice;
144 | try {
145 | //se abre el fichero para lectura/escritura
146 | fichero = new RandomAccessFile("texto.txt", "rw");
147 |
148 | //Se pide la palabra a buscar
149 | System.out.print("Introduce palabra: ");
150 | palabra = sc.nextLine().trim();
151 |
152 | //lectura del fichero
153 | cadena = fichero.readLine(); //leemos la primera línea
154 | while (cadena != null) { //mientras no lleguemos al final del fichero
155 | indice = cadena.indexOf(palabra); //buscamos la palabra en la línea leída
156 | while (indice != -1) { //mientras la línea contenga esa palabra (por si está repetida)
157 |
158 | //paso la línea a un StringBuilder para modificarlo
159 | auxBuilder = new StringBuilder(cadena);
160 | auxBuilder.replace(indice, indice + palabra.length(), palabra.toUpperCase());
161 | cadena = auxBuilder.toString();
162 |
163 | //nos posicionamos al principio de la línea actual y se sobrescribe la
164 | //línea completa
165 | //La posición donde empieza la línea actual la estoy guardando
166 | //en la variable pos
167 | fichero.seek(pos);
168 | fichero.writeBytes(cadena);
169 |
170 | //compruebo si se repite la misma palabra en la línea
171 | indice = cadena.indexOf(palabra);
172 | }
173 | pos = fichero.getFilePointer(); //posición de la línea actual que voy a leer
174 | cadena = fichero.readLine(); //lectura de la línea
175 | }
176 | } catch (FileNotFoundException ex) {
177 | System.out.println(ex.getMessage());
178 | } catch (IOException ex) {
179 | System.out.println(ex.getMessage());
180 | } finally {
181 | try {
182 | if (fichero != null) {
183 | fichero.close();
184 | }
185 | } catch (IOException e) {
186 | System.out.println(e.getMessage());
187 | }
188 | }
189 | }
190 | }
191 |
--------------------------------------------------------------------------------
/Soluciones/03-FicherosAccesoAleatorio/src/es/joseluisgs/dam/Main.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam;
2 |
3 | public class Main {
4 | public static void main(String[] args) {
5 | //EjemplosVarios.escribirEntero();
6 | //EjemplosVarios.modificarEntero();
7 | //EjemplosVarios.mostrarFichero();
8 | EjemplosVarios.palabras();
9 |
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/Soluciones/04-FicherosDirectorios/.gitignore:
--------------------------------------------------------------------------------
1 | /out
2 | /fichero.txt
--------------------------------------------------------------------------------
/Soluciones/04-FicherosDirectorios/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Datasource local storage ignored files
5 | /dataSources/
6 | /dataSources.local.xml
7 | # Editor-based HTTP Client requests
8 | /httpRequests/
9 |
--------------------------------------------------------------------------------
/Soluciones/04-FicherosDirectorios/.idea/description.html:
--------------------------------------------------------------------------------
1 | Simple Java application that includes a class with main() method
--------------------------------------------------------------------------------
/Soluciones/04-FicherosDirectorios/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Soluciones/04-FicherosDirectorios/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Soluciones/04-FicherosDirectorios/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Soluciones/04-FicherosDirectorios/.idea/project-template.xml:
--------------------------------------------------------------------------------
1 |
2 | IJ_BASE_PACKAGE
3 |
--------------------------------------------------------------------------------
/Soluciones/04-FicherosDirectorios/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
10 |
--------------------------------------------------------------------------------
/Soluciones/04-FicherosDirectorios/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Soluciones/04-FicherosDirectorios/06-FicherosDirectorios.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Soluciones/04-FicherosDirectorios/src/es/joseluisgs/dam/Main.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.util.Arrays;
6 |
7 | public class Main {
8 |
9 | public static void main(String[] args) throws IOException, IOException {
10 |
11 |
12 | //Creamos objetos File
13 | //Asegurate que existan
14 | File fichero=new File("06-FicherosDirectorios.iml"); // Debe existir
15 | File fichero2=new File("fichero.txt");
16 | File directorio=new File("src"); // Debe existir y llenalo de coSAS
17 | File directorio2=new File("directorio");
18 |
19 |
20 | //Indica si existen los archivos
21 | System.out.println("Existencia: ");
22 | System.out.println("Fichero "+fichero.exists());
23 | System.out.println("Directorio "+directorio.exists());
24 |
25 | System.out.println("");
26 |
27 | //Indica si son directorios
28 | System.out.println("¿Son directorios?: ");
29 | System.out.println("Fichero "+fichero.isDirectory());
30 | System.out.println("Directorio "+directorio.isDirectory());
31 |
32 | System.out.println("");
33 |
34 | //Indica si son ficheros
35 | System.out.println("¿Son ficheros?: ");
36 | System.out.println("Fichero "+fichero.isFile());
37 | System.out.println("Directorio "+directorio.isFile());
38 |
39 | System.out.println("");
40 |
41 | //Indica la ruta absoluta del fichero o directorio
42 | System.out.println("Ruta absoluta: ");
43 | System.out.println("Fichero "+fichero.getAbsolutePath());
44 | System.out.println("Directorio "+directorio.getAbsolutePath());
45 |
46 | System.out.println("");
47 |
48 | //Indica si se puede leer
49 | System.out.println("¿Se pueden leer?:");
50 | System.out.println("Fichero "+fichero.canRead());
51 | System.out.println("Directorio "+directorio.canRead());
52 |
53 | System.out.println("");
54 |
55 | //Indica si se puede escribir
56 | System.out.println("¿Se pueden escribir?:");
57 | System.out.println("Fichero "+fichero.canWrite());
58 | System.out.println("Directorio "+directorio.canWrite());
59 |
60 | System.out.println("");
61 |
62 | //Indica si se puede ejecutar
63 | System.out.println("¿Se pueden ejecutar?:");
64 | System.out.println("Fichero "+fichero.canExecute());
65 | System.out.println("Directorio "+directorio.canExecute());
66 |
67 | System.out.println("");
68 |
69 | //Indica el nombre sin rutas
70 | System.out.println("Nombres sin rutas: ");
71 | System.out.println("Fichero "+fichero.getName());
72 | System.out.println("Directorio "+directorio.getName());
73 |
74 | System.out.println("");
75 |
76 | //Indica el nombre del directorio padre
77 | System.out.println("Nombre del directorio padre: ");
78 | System.out.println("Fichero "+fichero.getParent());
79 | System.out.println("Directorio "+directorio.getParent());
80 |
81 | System.out.println("");
82 |
83 | //Guarda en un array de File los directorios hijos, solo con directorios
84 | System.out.println("Nombre de los objetos File dentro de un array");
85 | File lista[]=directorio.listFiles();
86 |
87 | for (File f: lista){
88 | System.out.println(f);
89 | }
90 |
91 | System.out.println("");
92 |
93 | //Guarda en un array de String los directorios hijos, solo con directorios
94 | System.out.println("Nombre de los objetos String dentro de un array");
95 | String listaString[]=directorio.list();
96 |
97 | for (String s : listaString) {
98 | System.out.println(s);
99 | }
100 |
101 | System.out.println("");
102 |
103 | //Crea el directorio (no existe)
104 | System.out.println("Creando directorio...");
105 | System.out.println(directorio2.mkdir());
106 |
107 | System.out.println("");
108 |
109 | //Crea el fichero (no existe), debe controlarse la excepcion (arriba lanzamos la excepcion)
110 | System.out.println("Creando fichero...");
111 | System.out.println(fichero2.createNewFile());
112 |
113 | // Copiar ficheros y directorios JAVA NIO2
114 | //Files.copy(path, out)
115 |
116 |
117 | // borrar ficheros o directorios
118 | //fichero.delete();
119 | //directorio.delete();
120 | //Files.deleteIfExists(path)
121 |
122 | // Enlaces y otras operaciones en la clase Files
123 | //Files.createLink(path, path1)
124 | //Files.size();
125 | // Files.move();
126 | // Files, .... bla bla bla
127 |
128 |
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/Soluciones/06-FicherosUtils/.gitignore:
--------------------------------------------------------------------------------
1 | /out
2 |
--------------------------------------------------------------------------------
/Soluciones/06-FicherosUtils/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Datasource local storage ignored files
5 | /dataSources/
6 | /dataSources.local.xml
7 | # Editor-based HTTP Client requests
8 | /httpRequests/
9 |
--------------------------------------------------------------------------------
/Soluciones/06-FicherosUtils/.idea/description.html:
--------------------------------------------------------------------------------
1 | Simple Java application that includes a class with main() method
--------------------------------------------------------------------------------
/Soluciones/06-FicherosUtils/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Soluciones/06-FicherosUtils/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Soluciones/06-FicherosUtils/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Soluciones/06-FicherosUtils/.idea/project-template.xml:
--------------------------------------------------------------------------------
1 |
2 | IJ_BASE_PACKAGE
3 |
--------------------------------------------------------------------------------
/Soluciones/06-FicherosUtils/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/Soluciones/06-FicherosUtils/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Soluciones/06-FicherosUtils/08-FicherosUtils.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Soluciones/06-FicherosUtils/src/es/joseluisgs/dam/Main.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam;
2 |
3 | import java.awt.*;
4 | import java.io.File;
5 | import java.net.URI;
6 |
7 | public class Main {
8 |
9 | public static void main(String[] args) {
10 | // abrir una aplicacion
11 | /*Runtime aplicacion = Runtime.getRuntime();
12 | try{
13 | aplicacion.exec("c:\\Program Files (x86)\\Notepad++\\notepad++.exe "+fichero2.getAbsolutePath());
14 | aplicacion.exec("c:\\Program Files (x86)\\Notepad++\\notepad++.exe "+fichero2.getAbsolutePath());
15 | }
16 | catch(Exception e)
17 | {
18 | System.err.println(e);
19 | }*/
20 |
21 | Desktop app = Desktop.getDesktop();
22 | try{
23 | app.edit(new File("prueba.txt"));
24 | app.mail();
25 | app.browse(new URI("https://joseluisgs.github.io/"));
26 | app.print(new File("prueba.txt"));
27 | }
28 | catch(Exception e)
29 | {
30 | System.err.println(e);
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Soluciones/07-Json-Gson/.gitignore:
--------------------------------------------------------------------------------
1 | out/
2 | target/
3 |
--------------------------------------------------------------------------------
/Soluciones/07-Json-Gson/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/Soluciones/07-Json-Gson/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/Soluciones/07-Json-Gson/.idea/description.html:
--------------------------------------------------------------------------------
1 | Simple Java application that includes a class with main() method
--------------------------------------------------------------------------------
/Soluciones/07-Json-Gson/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Soluciones/07-Json-Gson/.idea/jarRepositories.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/Soluciones/07-Json-Gson/.idea/libraries/Maven__com_google_code_gson_gson_2_9_0.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Soluciones/07-Json-Gson/.idea/libraries/Maven__org_projectlombok_lombok_1_18_22.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Soluciones/07-Json-Gson/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/Soluciones/07-Json-Gson/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Soluciones/07-Json-Gson/.idea/project-template.xml:
--------------------------------------------------------------------------------
1 |
2 | IJ_BASE_PACKAGE
3 |
--------------------------------------------------------------------------------
/Soluciones/07-Json-Gson/Json-Gson.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/Soluciones/07-Json-Gson/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | groupId
8 | Json-Gson
9 | 1.0-SNAPSHOT
10 |
11 |
12 | 11
13 | 11
14 |
15 |
16 |
17 |
18 |
19 | com.google.code.gson
20 | gson
21 | 2.9.0
22 |
23 |
24 |
25 | org.projectlombok
26 | lombok
27 | 1.18.22
28 | provided
29 |
30 |
31 | org.projectlombok
32 | lombok
33 | RELEASE
34 | compile
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/Soluciones/07-Json-Gson/src/main/java/es/joseluisgs/dam/Main.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam;
2 |
3 | import com.google.gson.Gson;
4 | import com.google.gson.GsonBuilder;
5 | import es.joseluisgs.dam.model.Menu;
6 | import es.joseluisgs.dam.model.Producto;
7 |
8 | import java.util.Arrays;
9 | import java.util.List;
10 | import java.util.Properties;
11 |
12 | public class Main {
13 |
14 | public static void main(String[] args) {
15 | System.out.println("Hola Json con Gson");
16 |
17 | // escribirJSON();
18 |
19 | leerJSON();
20 |
21 | }
22 |
23 | private static void leerJSON() {
24 | System.out.println("Leer un objeto JSON");
25 | var gson = new GsonBuilder().setPrettyPrinting().create();
26 | Producto p1 = new Producto("Patata", "Patata de la verdura", 1.5);
27 | String json = gson.toJson(p1);
28 | System.out.println(json);
29 | Producto result = gson.fromJson(json, Producto.class);
30 | System.out.println(result);
31 | if (result.equals(p1)) {
32 | System.out.println("Son iguales");
33 | }
34 |
35 | System.out.println("Leer una lista de objeto JSON");
36 | Producto p2 = new Producto("Tomate", "Tomate de la verdura", 2.5);
37 | List productos = List.of(p1, p2);
38 | json = gson.toJson(productos);
39 | System.out.println(json);
40 | List resultList = gson.fromJson(json, List.class);
41 | Producto[] resultArray = gson.fromJson(json, Producto[].class);
42 | System.out.println(resultList);
43 | System.out.println(Arrays.toString(resultArray));
44 |
45 | Menu m1 = new Menu("Menu 1", "Descripcion del menu 1", productos);
46 | Menu m2 = new Menu("Menu 2", "Descripcion del menu 2", productos);
47 | List