我正在尝试将对象保存到具有以下类的文件中,但它给了我 java.io.NotSerializableException。
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
class Saver {
Calendar cal = Calendar.getInstance();
public void save(ArrayList<Product> products) {
for (int i = 0; i < products.size(); i++) {
try {
FileOutputStream saveFile = new FileOutputStream(
"/" + products.get(i) + ".product"
);
ObjectOutputStream oos = new ObjectOutputStream(saveFile);
oos.writeObject(products.get(i));
} catch(Exception ex) {
System.out.println(ex);
}
}
}
}
而类 Product 看起来像这样:
class Product {
private String title;
private int id;
private double price;
public Product(String title, int id, double price) {
this.title = title;
this.id = id;
this.price = price;
}
public String getTitle() {
return title;
}
public int getId() {
return id;
}
public double getPrice() {
return price;
}
public void setTitle(String title) {
this.title = title;
}
public void setId(int id) {
this.id = id;
}
public void setPrice(double price) {
this.price = price;
}
}
我在做什么错,然后如何将对象存储在文件中?提前致谢!