Vin*_*lia 2 java serialization arraylist
我正在尝试序列化这个arraylist:
static ArrayList<Product> Chart=new ArrayList<Product>();
Run Code Online (Sandbox Code Playgroud)
与这些对象:
double Total;
String name;
double quantity;
String unit;
double ProductPrice
Run Code Online (Sandbox Code Playgroud)
这是到目前为止的课程:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我试图序列化和反序列化arraylist(在另一个类中声明),以便arraylist中的对象将在运行时之间保存.有任何想法吗?
为什么要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();
}
Run Code Online (Sandbox Code Playgroud)
阅读:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4880 次 |
| 最近记录: |