gpt4 book ai didi

Java 按日期保存对象

转载 作者:行者123 更新时间:2023-12-01 07:11:07 26 4
gpt4 key购买 nike

我试图将对象保存到具有以下类的文件中,但它给了我 java.io.NotSerializedException。

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

}

我做错了什么以及如何将对象存储在文件中?提前致谢!

最佳答案

您必须通过实现 Serializable 来序列化您的 Product 类接口(interface)是您要保存其状态的类的标记接口(interface)。

class Product implements Serializable {

tutorial Link for Object Serialization in java

关于Java 按日期保存对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14030062/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com