2012-08-06 61 views
2

我试图序列此ArrayList:如何序列化一个ArrayList

static ArrayList<Product> Chart=new ArrayList<Product>(); 

与这些对象:

double Total; 
String name; 
double quantity; 
String unit; 
double ProductPrice 

这是类到目前为止:

import java.io.IOException; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 
import java.io.Serializable; 

public class Product implements Serializable{ 
double Total; 
String name; 
double quantity; 
String unit; 
double ProductPrice; 

public Product(String n) 
{ 
    name=n; 
} 
private void writeObject(ObjectOutputStream s) throws IOException 
{ 
    s.defaultWriteObject(); 
    Product pt=new Product(name); 
    ObjectOutputStream oos=new ObjectOutputStream(s); 
    oos.writeObject(pt); 
} 
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException 
{ 
    s.defaultReadObject(); 
    Product pt; 
    ObjectInputStream ios =new ObjectInputStream(s); 
    ObjectInputStream ois = null; 
    pt=(Product)ois.readObject(); 
} 


} 

我尝试序列化和反序列化ArrayList(在另一个类中声明),以便ArrayList中的对象将在运行时间之间保存。有任何想法吗?

+3

'ArrayList'实现'Serializable' ...这是什么问题? – 2012-08-06 21:41:33

+0

不要让事情更难,如果他们能够simplier [如何使用西河库序列化列表以XML] [1] [1]:http://stackoverflow.com/questions/10051501/xstream-how-to-serialize -a-list-to-xml – dantuch 2012-08-06 21:44:05

回答

5

为什么你要在这些方法中创建新的Product对象?它们不是静态的,所以我会假设它们应该在this上运行?您也正试图在您刚刚设置为null的对象上调用readObject()

如果您可以提供有关您所看到的错误以及您如何使用这些错误的更多详细信息,那么我们可能会提供更多帮助。

编辑:增加了一些示例代码

写出来:

Product p = new Product("My Product"); 
    try 
    { 
     FileOutputStream fileOut = 
     new FileOutputStream("product.ser"); 
     ObjectOutputStream out = new ObjectOutputStream(fileOut); 
     out.writeObject(p); 
     out.close(); 
     fileOut.close(); 
    } catch(IOException ioe) 
    { 
     ioe.printStackTrace(); 
    } 

阅读它:

Product p = null; 
    try 
    { 
     FileInputStream fileIn = new FileInputStream("product.ser"); 
     ObjectInputStream in = new ObjectInputStream(fileIn); 
     p = (Product) in.readObject(); 
     in.close(); 
     fileIn.close(); 
    } catch(IOException ioe) 
    { 
     ioe.printStackTrace(); 
     return; 
    } catch(ClassNotFoundException c) 
    { 
     System.out.println(.Product class not found.); 
     c.printStackTrace(); 
     return; 
    } 
+0

我没有任何错误,我只是不知道该从哪里下去。这是我第一次使用序列化任何东西 – vman411gamer 2012-08-07 02:33:49

+0

好吧,我已经更新了这篇文章,展示了适合你的课堂的一些示例代码。您可以从类中移除读取和写入方法,并在'main'(或任何地方)使用此代码来写入或读取正在使用的对象。 – Carl 2012-08-07 04:36:14

0

ArrayList类已经实现Serializable,你让你的类(产品)可序列化;一切似乎写信给我。 “以便ArrayList中的对象将在运行时间之间保存。”你让它听起来像你认为它应该在每次运行时自动保存;这可能是你的错误。你必须把它写入一个文件,读取它的下一次执行(使用的ObjectOutput(/输入)流)

1

它看起来不像有任何需要Product提供readObjectwriteObject方法。您应该能够按原样序列化并反序列化List

我建议将这个列表包装在上下文中有意义的类中。 (我不知道上下文是什么,或者顺序是什么(Set会更好)。)另外,可变的静态方法通常是一个糟糕的主意,特别是如果您要尝试对引用的对象进行序列化和反序列化。