2013-04-22 37 views
6

xin chào các đồng nghiệp thân yêu,Deserialize nhiều đối tượng Java

Tôi có một lớp Garden trong đó tôi sắp xếp và deserialize nhiều đối tượng lớp thực vật. Việc serializing đang làm việc nhưng việc deserializing không hoạt động nếu muốn gán nó cho biến gọi trong phương thức tĩnh mein. đang

public void searilizePlant(ArrayList<Plant> _plants) { 
    try { 
     FileOutputStream fileOut = new FileOutputStream(fileName); 
     ObjectOutputStream out = new ObjectOutputStream(fileOut); 
     for (int i = 0; i < _plants.size(); i++) { 
      out.writeObject(_plants.get(i)); 
     } 
     out.close(); 
     fileOut.close(); 
    } catch (IOException ex) { 
    } 
} 

deserializing:

public ArrayList<Plant> desearilizePlant() { 
    ArrayList<Plant> plants = new ArrayList<Plant>(); 
    Plant _plant = null; 
    try { 
     ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName)); 
     Object object = in.readObject(); 

     // _plant = (Plant) object; 


     // TODO: ITERATE OVER THE WHOLE STREAM 
     while (object != null) { 
      plants.add((Plant) object); 
      object = in.readObject(); 
     } 

     in.close(); 
    } catch (IOException i) { 
     return null; 
    } catch (ClassNotFoundException c) { 
     System.out.println("Employee class not found"); 
     return null; 
    } 
    return plants; 
} 

đang cách gọi của tôi:

ArrayList<Plant> plants = new ArrayList<Plant>(); 
plants.add(plant1); 
Garden garden = new Garden(); 
garden.searilizePlant(plants); 

// THIS IS THE PROBLEM HERE 
ArrayList<Plant> dp = new ArrayList<Plant>(); 
dp = garden.desearilizePlant(); 

chỉnh sửa
tôi nhận được một ngoại lệ con trỏ null
Các giải pháp của @NilsH đang làm việc tốt, cảm ơn!

+0

Bạn có ý nghĩa gì bởi "nó không hoạt động"? Mã có biên dịch không? Bạn có gặp lỗi trong thời gian chạy không? Lỗi nào bạn nhận được chính xác? – Jesper

+0

Xin chào, bạn đang gặp phải sự cố chính xác nào? Ý bạn là gì, nó "không hoạt động nếu muốn gán nó cho biến gọi trong phương thức tĩnh (chính)"? Trong trình gỡ rối, bạn có thấy mảng 'thực vật' được xây dựng chính xác không? – wmorrison365

+0

Ngoài ra, bạn cần phải đặt các cuộc gọi đóng IO của bạn trong khối 'cuối cùng'. Và ngoài ra, bạn không cần 'ArrayList dp = new ArrayList ();'. Chỉ cần có 'ArrayList dp = garden.desearilizePlant();' khi mảng của bạn được tạo trong '# deserializePlant' – wmorrison365

Trả lời

16

Làm cách nào để tuần tự hóa toàn bộ danh sách? Không cần phải tuần tự hóa từng đối tượng riêng lẻ trong một danh sách.

public void searilizePlant(ArrayList<Plant> _plants) { 
    try { 
     FileOutputStream fileOut = new FileOutputStream(fileName); 
     ObjectOutputStream out = new ObjectOutputStream(fileOut); 
     out.writeObject(_plants); 
     out.close(); 
     fileOut.close(); 
    } catch (IOException ex) { 
    } 
} 

public List<Plant> deserializePlant() { 
    List<Plants> plants = null; 
    try { 
     ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName)); 
     plants = in.readObject(); 
     in.close(); 
    } 
    catch(Exception e) {} 
    return plants; 
} 

Nếu điều đó không giải quyết được sự cố của bạn, vui lòng đăng thêm chi tiết về lỗi của bạn.

+0

+1 Tôi muốn đi với điều đó ... – wmorrison365

+0

@NilsH cảm ơn rất nhiều nó làm việc thay đổi: công ** Danh sách ** deserializePlant() {....} – imalik8088

0

Có thể không phải lúc nào cũng khả thi để loại bỏ toàn bộ danh sách đối tượng (ví dụ: do vấn đề về bộ nhớ). Trong trường hợp này thử:

ObjectInputStream in = new ObjectInputStream(new FileInputStream(
      filename)); 

    while (true) { 
     try { 
      MyObject o = (MyObject) in.readObject(); 
      // Do something with the object 
     } catch (EOFException e) { 
      break; 
     } 
    } 

    in.close(); 

Hoặc sử dụng Java SE 7 try-với-nguồn lực tuyên bố:

try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(
      filename))) { 
     while (true) { 
      MyObject o = (MyObject) in.readObject(); 
      // Do something with the object 
     } 
    } catch (EOFException e) { 
     return; 
    } 
+0

Điều này không hiệu quả đối với tôi. Tôi gặp lỗi tham nhũng luồng. Xem http://stackoverflow.com/questions/23889486/java-io-streamcorruptedexception-wrong-format-when-reading-more-than-1-object – faizal

+0

@faizal Cần phải sửa đổi cách tạo luồng đầu ra. Xem http://stackoverflow.com/questions/1194656/appending-to-an-objectoutputstream – Tomasz

+0

Của nó vì điều kiện trong khi bạn. Bạn sẽ đọc từ luồng mặc dù nó đã được tiêu thụ. –

0

Nếu bạn serialize nó vào một danh sách mảng tuyến tính, bạn có thể cast nó trở lại một mảng danh sách tuyến tính khi deserializing nó - tất cả các phương pháp khác không thành công cho tôi:

import java.io.*; 
import java.util.ArrayList; 
import java.util.Arrays; 

public class Program 
{ 
    public static void writeToFile(String fileName, Object obj, Boolean appendToFile) throws Exception 
    { 
     FileOutputStream fs = null; 
     ObjectOutputStream os = null; 
     try 
     { 
      fs = new FileOutputStream(fileName); 
      os = new ObjectOutputStream(fs); 

      //ObjectOutputStream.writeObject(object) inherently writes binary 
      os.writeObject(obj); //this does not use .toString() & if you did, the read in would fail 
     } 
     catch (FileNotFoundException e) 
     { 
      e.printStackTrace(); 
     } 
     catch (IOException e) 
     { 
      e.printStackTrace(); 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 
     finally 
     { 
      try 
      { 
       os.close(); 
       fs.close(); 
      } 
      catch(Exception e) 
      { 
       //if this fails, it's probably open, so just do nothing 
      } 
     } 
    } 


    @SuppressWarnings("unchecked") 
    public static ArrayList<Person> readFromFile(String fileName) 
    { 
     FileInputStream fi = null; 
     ObjectInputStream os = null; 
     ArrayList<Person> peopleList = null; 
     try 
     { 
      fi = new FileInputStream(fileName); 
      os = new ObjectInputStream(fi); 
      peopleList = ((ArrayList<Person>)os.readObject()); 
     } 
     catch (FileNotFoundException e) 
     { 
      e.printStackTrace(); 
     } 
     catch(EOFException e) 
     {      
      e.printStackTrace(); 
     } 
     catch(ClassNotFoundException e) 
     { 
      e.printStackTrace(); 
     } 
     catch (IOException e) 
     { 
      e.printStackTrace(); 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 
     finally 
     { 
      try 
      { 
       os.close(); 
       fi.close(); 
      } 
      catch(Exception e) 
      { 
       //if this fails, it's probably open, so just do nothing 
      } 
     } 
     return peopleList; 
    } 




    public static void main(String[] args) 
    { 
     Person[] people = { new Person(1, 39, "Coleson"), new Person(2, 37, "May") }; 
     ArrayList<Person> peopleList = new ArrayList<Person>(Arrays.asList(people)); 

     System.out.println("Trying to write serializable object array: "); 

     for(Person p : people) 
     { 
      System.out.println(p); 
     } 
     System.out.println(" to binary file"); 

     try 
     { 
      //writeToFile("output.bin", people, false); //serializes to file either way 
      writeToFile("output.bin", peopleList, false); //but only successfully read back in using single cast 
     }            // peopleList = (ArrayList<Person>)os.readObject(); 
                 // Person[] people = (Person[])os.readObject(); did not work 
                 // trying to read one at a time did not work either (not even the 1st object) 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 



     System.out.println("\r\n"); 




     System.out.println("Trying to read object from file. "); 
     ArrayList<Person> foundPeople = null; 
     try 
     { 
      foundPeople = readFromFile("input.bin"); 
     } 
     catch (Exception e) 
     { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     if (foundPeople == null) 
     { 
      System.out.println("got null, hummm..."); 
     } 
     else 
     { 
      System.out.println("found: "); 

      for(int i = 0; i < foundPeople.size(); i++) 
      { 
       System.out.println(foundPeople.get(i)); 
      } 

      //System.out.println(foundPeople); //implicitly calls .toString() 
     } 
    } 
} 
Các vấn đề liên quan