如何序列化arraylist

时间:2012-08-06 21:39:09

标签: java serialization 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 个答案:

答案 0 :(得分:5)

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

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

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

写出来:

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

答案 1 :(得分:1)

Product提供readObjectwriteObject方法似乎不需要List。您应该能够按原样序列化和反序列化Set

我建议将列表包装在一个在上下文中有意义的类中。 (我不知道上下文是什么,或者命令是什么({{1}}会更好)。)同样可变的静态通常是一个坏主意,特别是如果你要尝试序列化和反序列化引用的对象。

答案 2 :(得分:0)

ArrayList类已经实现了Serializable,你使你的类(Product)可序列化;一切似乎写信给我。 “这样,arraylist中的对象将在运行时间之间保存。”你让它听起来像你认为它应该在你每次运行之间自动保存它们;这可能是你的错。您必须将其写入文件,并在下次执行时读取它(使用ObjectOutput(/ Input)Streams)