Java - Ayuda en un programa que almacene en dos .dat personas(edad y nombre)

 
Vista:
sin imagen de perfil

Ayuda en un programa que almacene en dos .dat personas(edad y nombre)

Publicado por Sergio (1 intervención) el 06/11/2017 18:57:33
Buenas, necesito ayuda, estoy creando un programa que almacene en dos .dat personas(edad y nombre), y luego estos dos los grabe en unico fichero.
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fichaleatorio;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.util.Scanner;
 
/**
 *
 * @author sergi
 */
public class FichAleatorio {
 static Scanner entrada = new Scanner (System.in);
     static int i = 0;
     static String nombre;
     static int edad;
     static int telefono;
     static String Fichero;
     static String Fichero2;
     static String Fichero3;
    static int opcion;
 
 
        //CODIGO REUTILIZADO DE PROYECTO JOSE//
    private static RandomAccessFile flujo;
    private static int numeroRegistros;
    private static int tamañoRegistro = 80;
 
    public static void crearFileAlumno(File archivo) throws IOException {
        if (archivo.exists() && !archivo.isFile()) {
            throw new IOException(archivo.getName() + " no es un archivo");
        }
        flujo = new RandomAccessFile(archivo, "rw");
        numeroRegistros = (int) Math.ceil(
                (double) flujo.length() / (double) tamañoRegistro);
    }
 
    public static void cerrar() throws IOException {
        flujo.close();
    }
 
    public static boolean setPersona(int i, Persona persona) throws IOException {
        if(i >= 0 && i <= getNumeroRegistros()) {
            if(persona.getTamaño() > tamañoRegistro) {
                System.out.println("\nTamaño de registro excedido.");
            } else {
                flujo.seek(i*tamañoRegistro);
                flujo.writeUTF(persona.getNombre());
                flujo.writeInt(persona.getEdad());
                flujo.writeBoolean(persona.isActivo());
                return true;
            }
        } else {
            System.out.println("\nNúmero de registro fuera de límites.");
        }
        return false;
    }
 
    private static int buscarRegistroInactivo() throws IOException {
        String nombre;
        for(int i=0; i<getNumeroRegistros(); i++)
        {
            flujo.seek(i * tamañoRegistro);
            if(!getPersona(i).isActivo())
                return i;
        }
        return -1;
    }
 
    public static void añadirPersona(Persona persona) throws IOException {
        int inactivo = buscarRegistroInactivo();
        if(setPersona(inactivo==-1?numeroRegistros:inactivo, persona))
            numeroRegistros++;
    }
 
    public static int getNumeroRegistros() {
        return numeroRegistros;
    }
 
    public static Persona getPersona(int i) throws IOException {
        if(i >= 0 && i <= getNumeroRegistros()) {
            flujo.seek(i * tamañoRegistro);
            return new Persona(flujo.readUTF(), flujo.readInt(), flujo.readBoolean());
        } else {
            System.out.println("\nNúmero de registro fuera de límites.");
            return null;
        }
    }
 
    public static int buscarRegistro(String buscado) throws IOException {
        Persona p;
        if (buscado == null) {
            return -1;
        }
        for(int i=0; i<getNumeroRegistros(); i++) {
            flujo.seek(i * tamañoRegistro);
            p = getPersona(i);
            if(p.getNombre().equals(buscado) && p.isActivo()) {
                return i;
            }
        }
        return -1;
    }
 
    public static void leerDatos(String archivo){
 
        try{
 
        String texto = new String();
        FileReader fr = new FileReader(archivo);
        BufferedReader entrada = new BufferedReader(fr);
        String a;
 
        while ((a = entrada.readLine()) != null){
 
            texto += a + "\n";
 
        }
 
            entrada.close();
 
            System.out.println("\nDatos Leidos del archivo: \n" + texto);
 
 
        }catch(FileNotFoundException fnfex)
 
        {
            System.out.println("Archivo no Encontrado !!!" + fnfex);
 
        }catch (IOException ioex){
 
            System.err.println("Error");
 
        }
 
    }
 
    public static void grabarDatos(String archivo){
 
 
        try{
 
        String texto = new String();
        FileReader fr = new FileReader(archivo);
        BufferedReader entrada = new BufferedReader(fr);
        FileWriter fw = new FileWriter(archivo, true);
        BufferedWriter bw = new BufferedWriter(fw);
        String a;
 
        while ((a = entrada.readLine()) != null){
 
            texto += a + "\n";
            bw.write(texto);
 
        }
 
            entrada.close();
            bw.close();
 
            System.out.println(texto);
 
 
        }catch(FileNotFoundException fnfex)
 
        {
            System.out.println("Archivo no Encontrado !!!" + fnfex);
 
        }catch (IOException ioex){
 
            System.err.println("Error");
 
        }
 
    }
 
public static void LecturaEscritura2(String ficheroOriginal, String ficheroCopia){
try
{
 
	int leidos = 0;
	boolean si_no = false;
 
	// Se abre el fichero donde se hará la copia
	FileOutputStream fileOutput = new FileOutputStream (ficheroCopia, si_no);
	BufferedOutputStream bufferedOutput = new BufferedOutputStream(fileOutput);
 
 
	System.out.println("FICHERO: "+ficheroOriginal);
 
	// Se abre el fichero original para lectura
 
	FileInputStream fileInput = new FileInputStream(ficheroOriginal);
	BufferedInputStream bufferedInput = new BufferedInputStream(fileInput);
 
	// Bucle para leer de un fichero y escribir en el otro.
 
	byte [] array = new byte[1000];
	leidos = bufferedInput.read(array);
 
	while (leidos > 0)
	{
		bufferedOutput.write(array, 0,leidos);
		leidos=bufferedInput.read(array);
 
	}
 
	// Cierre de los ficheros
 
	bufferedInput.close();
	bufferedOutput.close();
 
	}
		catch (Exception e)
	{
		e.printStackTrace();
	}
}
 
 
 
public static void LecturaEscritura(String archivo, String destino) throws FileNotFoundException, IOException {
    FileReader origen = new FileReader(archivo);
    FileWriter fw = new FileWriter(destino);
    String texto = new String();
    BufferedReader entrada = new BufferedReader(origen);
    BufferedWriter bw = new BufferedWriter(fw);
    String a;
    String b;
    try {
 
        while ((a = entrada.readLine()) != null){
 
            texto += a + "\n";
            bw.write(texto);
 
        }
 
        entrada.close();
        bw.close();
 
        System.out.println(texto);
 
    } catch (IOException ioe) {
        ioe.printStackTrace();
 
    }
 
}
 
 
 
 
 
    //CODIGO REUTILIZADO DE PROYECTO JOSE//
 
    public static void main(String[] args) throws IOException {
    menu();
}
public static void menu() throws IOException{
    do{
 
        System.out.println("**********************");
        System.out.println("1. INTRODUCIR DATOS");
        System.out.println("2. GRABACIÓN DE DATOS");
        System.out.println("3. LECTURA DE DATOS");
        System.out.println("4. SALIR");
        System.out.println("**********************");
 
        System.out.println("Dime una opcion");
 
        opcion = entrada.nextInt();
        switch(opcion) {
 
            case 1:
                introducirdatos();
            case 2:
                grabardatos();
            case 4:
                break;
 
        }
    }while(opcion !=4);
}
 
public static void introducirdatos() throws IOException{
	do{
	    System.out.println("**********************");
	    System.out.println("ELIGE UN FICHERO");
	    System.out.println("1. FICHERO 1");
	    System.out.println("2. FICHERO 2");
	    System.out.println("3. SALIR");
 
	    opcion = entrada.nextInt();
 
	    switch(opcion){
 
	        case 1:
	            System.out.println("******************");
	            System.out.println("ESCRIBIR FICHERO");
	            System.out.println("Dime nombre del fichero");
	            Fichero = entrada.next();
	            System.out.println("*******************");
	            //CREA EL FICHERO LLAMANDO AL METODO crearFileAlumno insertado anteriormente en el código.
	            crearFileAlumno( new File(Fichero+".dat") );
 
	            do{
	            System.out.println("¿Deseas introducir un alumno?");
	            System.out.println("1. SI");
	            System.out.println("2. NO");
	            opcion = entrada.nextInt();
	            switch(opcion){
	                 case 1:
	                 System.out.println("Dime el nombre del alumno");
	                 nombre = entrada.next();
	                 System.out.println("Dime la edad");
	                 edad = entrada.nextInt();
 
	                 añadirPersona( new Persona(nombre, edad, true) );
 
	                }
	            }while(opcion !=2);
                menu();
 
	           System.out.println("**********************");
 
	        case 2:
	            System.out.println("******************");
	            System.out.println("ESCRIBIR FICHERO");
	            System.out.println("Dime el nombre del fichero");
	            Fichero2 = entrada.next();
	            crearFileAlumno( new File(Fichero2+".dat") );
	            do{
	            System.out.println("¿Deseas introducir un alumno?");
	            System.out.println("1. SI");
	            System.out.println("2. NO");
	            opcion = entrada.nextInt();
 
	            switch(opcion){
	            case 1:
 
	            System.out.println("Dime el nombre del alumno");
	            nombre = entrada.next();
	            System.out.println("Dime la edad");
	            edad = entrada.nextInt();
 
	            añadirPersona( new Persona(nombre, edad, true) );
 
	            }
	            }while(opcion !=2);
	                        menu();
 
	           System.out.println("**********************");
	    }
	}while(opcion !=3);
	menu();
}
 
public static void grabardatos() throws IOException{
    do{
    System.out.println("**************");
    System.out.println("¿Desea grabar realmente los datos?");
    System.out.println("1. SI");
    System.out.println("2. NO");
    opcion = entrada.nextInt();
    switch(opcion){
        case 1:
            System.out.println("**********************");
            System.out.println("Dime el nombre del archivo en el que quieres escribir");
            Fichero3 = entrada.next();
            crearFileAlumno( new File(Fichero3) );
            System.out.println("Dime nombres de los ficheros que buscas");
            System.out.println("1");
            Fichero = entrada.next();
            LecturaEscritura2(Fichero, Fichero3);
            System.out.println("2");
            Fichero2 = entrada.next();
            LecturaEscritura2(Fichero2, Fichero3);
 
    }
    }while(opcion !=2);
    menu();
}
 
}

El problema surge en que un fichero me sustituye al otro en el tercero (nuevo).

Esta es la clase persona:
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
package fichaleatorio;
 
import java.io.Serializable;
 
public class Persona implements Serializable {
    private String nombre; // cada caracter ocupa 2 bytes
    private int edad; // ocupa 4 bytes
    private boolean activo;
 
    public Persona() {
        nombre = "NN";
        edad = 0;
        activo = true;
    }
 
    public Persona(String nombre, int edad, boolean activo) {
        this.nombre = nombre;
        this.edad = edad;
        this.activo = activo;
    }
 
    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
 
    public String getNombre() {
        return nombre;
    }
 
    public void setEdad(int edad) {
        this.edad = edad;
    }
 
    public int getEdad() {
        return edad;
    }
 
    public boolean isActivo() {
        return activo;
    }
 
    public void setActivo(boolean activo) {
        this.activo = activo;
    }
 
    @Override
    public String toString() {
        return "\nNombre: " + nombre +
                "\nEdad: " + edad;
    }
 
    public int getTamaño() {
        return getNombre().length()*2 + 2 + 4 + 1;
    }
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder