lectura y escritura de HashSet en ficheros
Publicado por J.Manuel (10 intervenciones) el 08/05/2021 12:07:09
Buenas, en el siguiente código estoy intentado mediante dos métodos escribir y leer clientes que almaceno en archivo, pero a pesar de que uso un HashSet lo clientes se me duplican. ¿Alguna idea de dónde está mi error?
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
public static void EscribirFichero(Cliente cl) {
ObjectOutputStream objectOutput = null;
ObjectInputStream objectInput = null;
HashSet<Cliente> cliHS = new HashSet<Cliente>();
try {
if(FILE_NAME.exists()) {
objectInput = new ObjectInputStream(new FileInputStream(FILE_NAME));
cliHS = (HashSet<Cliente>) objectInput.readObject();
}
cliHS.add(cl);
objectOutput = new ObjectOutputStream(new FileOutputStream(FILE_NAME)); /// true
objectOutput.writeObject(cliHS);
System.out.println("Se ha generado el fichero " + FILE_NAME);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (objectOutput != null) {
try {
objectOutput.close();
} catch (IOException ignored) {
}
}
}
}
public static void LeerFichero() {
ObjectInputStream objectInput = null;
try {
objectInput = new ObjectInputStream(new FileInputStream(FILE_NAME));
Object actual = null;
HashSet<Cliente> cliHS = null;
while((actual = objectInput.readObject()) != null) {
cliHS = (HashSet<Cliente>) actual;
Iterator it = cliHS.iterator();
while(it.hasNext()) {
System.out.println("Datos cliente: "+it.next());
}
}
objectInput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(EOFException e) {
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (objectInput != null) {
try {
objectInput.close();
} catch (IOException ignored) {
}
}
}
}
Valora esta pregunta


0