2015-11-05 3 views
-1

У меня проблема, я хотел бы сериализовать ArrayList с Java в файл. , то я хотел бы десериализовать его на новый ArrayList и продолжить добавлять в ArrayList.ArrayList Serializable с Java

Когда я десериализую, он не загружается в ArrayList, он просто печатает содержимое файла. Это мой код: Вот класс ArrayList

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(); 
       } 

      } 
+0

Возможный дубликат [Сериализация ArrayList Java] (http://stackoverflow.com/questions/8785955/serialization-arraylist-java) – Tgsmith61591

+0

Как вы имеете в виду –

ответ

0

Я решить мою проблему! Теперь я могу редактировать своих клиентов! Спасибо за помощь и совет.

public class file { 

// Get all persons in file 
public List<Customers> getAllPersons(String fileLocation) { 
     List<Customers> localPersons = new ArrayList<>(); 

    try { 
     File f = new File(fileLocation); 
     FileInputStream fis = new FileInputStream(f); 
     ObjectInputStream ois = new ObjectInputStream(fis); 

     try { 
      while (true) { 
       localPersons.add((Customers) ois.readObject()); 
      } 
     } catch (EOFException e) { 

     } 
    } catch (IOException iOException) { 
    } catch (ClassNotFoundException classNotFoundException) { 
    } 

     return localPersons; 
} 

// Get person on personId in file 
public Customers getPersonOnPersonId(String fileLocation, int personId) { 
    Customers localPerson = null; 

    try { 
     File f = new File(fileLocation); 
     FileInputStream fis = new FileInputStream(f); 
     ObjectInputStream ois = new ObjectInputStream(fis); 

     try { 
      while (true) { 
       Customers tempPerson = (Customers) ois.readObject(); 

       if(personId == tempPerson.getPersonId()) { 
        localPerson = tempPerson; 
        break; 
       } 
      } 
     } catch (EOFException e) { 

     } 
    } catch (IOException iOException) { 
    } catch (ClassNotFoundException classNotFoundException) { 
    } 

    return localPerson; 
} 

// Get persons on firstname in file 
public List<Customers> getPersonsOnFirstName(String fileLocation, String firstName) { 
    List<Customers> localPersons = new ArrayList<>(); 

    try { 
     File f = new File(fileLocation); 
     FileInputStream fis = new FileInputStream(f); 
     ObjectInputStream ois = new ObjectInputStream(fis); 

     try { 
      while (true) { 
       Customers tempPerson = (Customers) ois.readObject(); 

       if(firstName.equals(tempPerson.getFirstName())) { 
        localPersons.add(tempPerson); 
       } 
      } 
     } catch (EOFException e) { 

     } 
    } catch (IOException iOException) { 
    } catch (ClassNotFoundException classNotFoundException) { 
    } 

    return localPersons; 
} 

// Get persons on lastname in file 
public List<Customers> getPersonsOnLastName(String fileLocation, String lastName) { 
    List<Customers> localPersons = new ArrayList<>(); 

    try { 
     File f = new File(fileLocation); 
     FileInputStream fis = new FileInputStream(f); 
     ObjectInputStream ois = new ObjectInputStream(fis); 

     try { 
      while (true) { 
       Customers tempPerson = (Customers) ois.readObject(); 

       if(lastName.equals(tempPerson.getLastName())) { 
        localPersons.add(tempPerson); 
       } 
      } 
     } catch (EOFException e) { 

     } 
    } catch (IOException iOException) { 
    } catch (ClassNotFoundException classNotFoundException) { 
    } 

    return localPersons; 
} 

// Insert person in file 
public void insertPerson(String fileLocation, Customers person) { 
    List<Customers> localPersons = new ArrayList<>(); 

    // Select block ************************************************ 
    int maxPersonId = 0; 

    try { 
     File f = new File(fileLocation); 
     FileInputStream fis = new FileInputStream(f); 
     ObjectInputStream ois = new ObjectInputStream(fis); 

     try { 
      while (true) { 
       Customers tempPerson = (Customers) ois.readObject(); 
       localPersons.add(tempPerson); 
       if(maxPersonId < tempPerson.getPersonId()) { 
        maxPersonId = tempPerson.getPersonId(); 
       } 
      } 
     } catch (EOFException e) { 

     } 
    } catch (IOException iOException) { 
    } catch (ClassNotFoundException classNotFoundException) { 
    } 
    // ************************************************************* 

    // Set primary key value to the person block ******************* 
    if(localPersons.isEmpty()) { 
     person.setPersonId(1); 
    } else { 
     maxPersonId++; 
     person.setPersonId(maxPersonId); 
    } 
    // ************************************************************* 

    // Insert block ************************************************ 
    try { 
     File f = new File(fileLocation); 
     FileOutputStream fos = new FileOutputStream(f); 
     ObjectOutputStream oos = new ObjectOutputStream(fos); 

     FileInputStream fis = new FileInputStream(f); 
     ObjectInputStream ois = new ObjectInputStream(fis); 

     localPersons.add(person); 

     for(Customers p : localPersons) { 
      oos.writeObject(p); 
     } 
    } catch (FileNotFoundException fileNotFoundException) { 
     System.out.println(fileNotFoundException.getMessage()); 
    } catch (IOException ioexception) { 
     System.out.println(ioexception.getMessage()); 
    } 
    // ************************************************************* 
} 

// Update person in file 
public void updatePerson(String fileLocation, Customers person) { 
    List<Customers> localPersons = new ArrayList<>(); 

    // Select block ************************************************ 
    try { 
     File f = new File(fileLocation); 
     FileInputStream fis = new FileInputStream(f); 
     ObjectInputStream ois = new ObjectInputStream(fis); 

     try { 
      while (true) { 
       Customers tempPerson = (Customers) ois.readObject(); 
       if(person.getPersonId() != tempPerson.getPersonId()) { 
        localPersons.add(tempPerson); 
       } else { 
        localPersons.add(person); 
       } 
      } 
     } catch (EOFException e) { 

     } 
    } catch (IOException iOException) { 
    } catch (ClassNotFoundException classNotFoundException) { 
    } 
    // ************************************************************* 

    // Insert block ************************************************ 
    try { 
     File f = new File(fileLocation); 
     FileOutputStream fos = new FileOutputStream(f); 
     ObjectOutputStream oos = new ObjectOutputStream(fos); 

     FileInputStream fis = new FileInputStream(f); 
     ObjectInputStream ois = new ObjectInputStream(fis); 

     for(Customers p : localPersons) { 
      oos.writeObject(p); 
     } 
    } catch (FileNotFoundException fileNotFoundException) { 
     System.out.println(fileNotFoundException.getMessage()); 
    } catch (IOException ioexception) { 
     System.out.println(ioexception.getMessage()); 
    } 
    // ************************************************************* 
} 

// Delete person in file 
public void deletePerson(String fileLocation, int personId) { 
    List<Customers> localPersons = new ArrayList<>(); 

    // Select block ************************************************ 
    try { 
     File f = new File(fileLocation); 
     FileInputStream fis = new FileInputStream(f); 
     ObjectInputStream ois = new ObjectInputStream(fis); 

     try { 
      while (true) { 
       Customers tempPerson = (Customers) ois.readObject(); 
       if(personId != tempPerson.getPersonId()) { 
        localPersons.add(tempPerson); 
       } 
      } 
     } catch (EOFException e) { 

     } 
    } catch (IOException iOException) { 
    } catch (ClassNotFoundException classNotFoundException) { 
    } 
    // ************************************************************* 

    // Insert block ************************************************ 
    try { 
     File f = new File(fileLocation); 
     FileOutputStream fos = new FileOutputStream(f); 
     ObjectOutputStream oos = new ObjectOutputStream(fos); 

     FileInputStream fis = new FileInputStream(f); 
     ObjectInputStream ois = new ObjectInputStream(fis); 

     for(Customers p : localPersons) { 
      oos.writeObject(p); 
     } 
    } catch (FileNotFoundException fileNotFoundException) { 
     System.out.println(fileNotFoundException.getMessage()); 
    } catch (IOException ioexception) { 
     System.out.println(ioexception.getMessage()); 
    } 
    // ************************************************************* 
} 
} 
-1

Это потому, что ваш arralylist инициализируется снова изменить его частный статический финал это сделает ваш день

private static final ArrayList<Customer> customers = new ArrayList(); 
+0

Великий будет пытаться это надеяться, что это работает –

+0

Что? Нет. Предполагается, что это переменная экземпляра 'Customers'. В любом случае, универсальная статика - плохая идея. –

0

Проблема с этот метод:

public void takeOutObjectFromFile(Customers customers) { 
     ... 
      customers = (Customers) ois.readObject(); 
     ... 
    } 

Вы просто перезаписали локальную переменную. То, что вы должны иметь это:

public Customers takeOutObjectFromFile() { 
     ... 
      return (Customers) ois.readObject(); 
     ... 
    } 

(. Кроме того, использование примерочных с-ресурс, чтобы убедиться, что вы закрыли файлы во всех случаях)

Смежные вопросы