I am trying to save an object to a file with the class below but it gives me 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);
}
}
}
}
Whereas the class Product looks like this:
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;
}
}
what am I doing wrong and how can I store the objects in a file then?
Thanks in advance!
As the exception says, the class (
Productin this case) isn’t serializable. You can probably just get away with this change:but you should also consider declaring a
serialVersionUIDfield for versioning purposes. Read the docs forSerializableand the serialization tutorial for a lot more detail. You don’t need to write any new members – it’s just a marker interface – but there are other methods you can add to give more control over serialization and deserialization.You should also consider alternative serialization approaches – personally I like Google Protocol Buffers, but I’m biased 🙂 Consider what versioning you’ll need, and any cross-platform support.
Additionally:
Product.toString()implicitly in the filename, but that won’t give you anything useful. What do you want the filename to be based on?cal– how do you want the current date/time to be stored?