I have a problem, I'd like to serialize an ArrayList
with Java to a file.
then I'd like to deserialize it to a new ArrayList
and continue to add to the ArrayList
.
When I deserialize, it doesn't load in the ArrayList
, it just prints the file contents. This is my code:
here is the arraylist class
public class Customers implements Serializable{
ArrayList<Customer> customers = new ArrayList();
ArrayList<Customer> customers2 = new ArrayList();
public void add(Customer customerIn) {
customers.add(customerIn);
}
public void remove(Customer customerIn) {
customers.remove(customerIn);
}
public Customer findByName(String firstName, String address) {
//För varje Customer i customers
for (Customer customer : customers) {
if (firstName.equals(customer.getName())) {
if (address.equals(customer.getAddress())) {
return customer;
}
}
}
return null;
}
class for seriallize and deserialize
public class file {
public void saveObjectsToFile(Customers customers) {
try{
FileOutputStream fos= new FileOutputStream("a.listFile");
ObjectOutputStream oos= new ObjectOutputStream(fos);
oos.writeObject(customers);
oos.close();
fos.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
public void takeOutObjectFromFile(Customers customers) {
try
{
FileInputStream fis = new FileInputStream("a.listFile");
ObjectInputStream ois = new ObjectInputStream(fis);
customers = (Customers) ois.readObject();
ois.close();
fis.close();
//
System.out.println(customers);
}catch(IOException ioe){
ioe.printStackTrace();
return;
}catch(ClassNotFoundException c){
System.out.println("Class not found");
c.printStackTrace();
return;
}
}
class for customer
//klass customer startar här.
public class Customer implements Serializable{
//Variabler int och String för kund id, namn, adress och telefon.
int CustomerID;
String customerName, customerAddress, customerPhone, Order;
//Konstruktor för klassen
public Customer(String Name, String Address, String Phone, String Order) {
this.customerName = Name;
this.customerAddress = Address;
this.customerPhone = Phone;
this.CustomerID = 100001;
this.Order = Order;
}
//Hämtar och sätter personuppgifter.
public String getName() { return this.customerName; }
public String getAddress() { return this.customerAddress; }
public String getPhone() { return this.customerPhone; }
public int getID() { return this.CustomerID; }
public String getOrder() { return this.Order; }
//Skriver ut kontroll av personuppgifter.
public void printPerson() {
System.out.println("\n\nKONTROLL AV UPPGIFTER\n");
System.out.println("Namn:\t\t\t" + getName());
System.out.println("Adress:\t\t\t" + getAddress());
System.out.println("Telefonnummer:\t\t" + getPhone());
System.out.println("KundID:\t\t\t" + getID());
System.out.println("Order:\t\t\t" + getOrder());
}
public String toString() {
return getName() + " " + getAddress() + " " + getPhone();
}
}