I have this problem: I want to add an ArrayList object to a file "clientes.dat" in order to store information on that file and display it later. However, whenever I write to said file again, the new ArrayList object overwrites the first one.
Here's the code:
import java.io.*;
import java.util.ArrayList;
public class Archivo implements Serializable{
private static final long serialVersionUID = 1L;
public static void nuevoCliente(Cliente cliente){
Cliente wo=cliente;
File f = new File("clientes.dat");
ArrayList<Cliente> woi=new ArrayList<>();
try {
FileOutputStream fop=new FileOutputStream(f);
ObjectOutputStream oos=new ObjectOutputStream(fop);
woi.add(wo);
oos.writeObject(woi);
oos.close();
} catch (IOException e) {
System.out.println("El Cliente no pudo ser agregado.");
}
}
@SuppressWarnings("unchecked")
public static void leerCliente() throws IOException, ClassNotFoundException{
try {
FileInputStream fis=new FileInputStream("clientes.dat");
ObjectInputStream ois=new ObjectInputStream(fis);
ArrayList<Cliente> woi=new ArrayList<>();
woi=(ArrayList<Cliente>)ois.readObject();
for(int i=0;i<woi.size();i++){
System.out.println(woi.get(i).getNombre());
}
ois.close();
}catch(IOException e){
System.out.println("El archivo no se pudo leer");
}
}
}
I have tried using FileOutputStream fop=new FileOutputStream(f, true);
But if I do it that way, the leerCliente() method will only return the first ArrayList that was stored, not the new one.