gpt4 book ai didi

Java 序列化无法按预期工作

转载 作者:行者123 更新时间:2023-11-30 06:30:58 25 4
gpt4 key购买 nike

我正在尝试序列化 ArrayList<Prescription>使用 ObjectOutputStream

这是 Prescription类:

import java.io.Serializable;
import java.util.Calendar;

public class Prescription implements Serializable {

private static final long serialVersionUID = 4432845389029948144L;

private String name;
private String dosage;
private int originalQuantity = 0;
private int quantityRemaining = 0;
private String prescribingPharmacy;

private long dateStarted = 0;

private boolean taken_AM = false;
private boolean taken_Noon = false;
private boolean taken_PM = false;

private boolean taken_Mon = false;
private boolean taken_Tue = false;
private boolean taken_Wed = false;
private boolean taken_Thu = false;
private boolean taken_Fri = false;
private boolean taken_Sat = false;
private boolean taken_Sun = false;

public Prescription(){
this.name = "Unknown";
}

public Prescription(String name, String dosage, int quantity, String pharmacy){
this.name = name;
this.dosage = dosage;
this.originalQuantity = quantity;
this.quantityRemaining = quantity;
this.prescribingPharmacy = pharmacy;
this.dateStarted = Calendar.getInstance().getTimeInMillis();
}

public void setTaken(boolean AM, boolean Noon, boolean PM){
this.taken_AM = AM;
this.taken_Noon = Noon;
this.taken_PM = PM;
}

public void setTaken(boolean Mon, boolean Tue, boolean Wed, boolean Thu,
boolean Fri, boolean Sat, boolean Sun){
this.taken_Mon = Mon;
this.taken_Tue = Tue;
this.taken_Wed = Wed;
this.taken_Thu = Thu;
this.taken_Fri = Fri;
this.taken_Sat = Sat;
this.taken_Sun = Sun;
}

public String getName(){
return this.name;
}

}

然而,当我尝试这样做时,我得到一个 NotSerializableExceptionPrescription 上类(class)。这对我来说没有任何意义,因为我只使用原始数据类型和 String .

这是我用来进行序列化的函数:

public boolean saveToFile(){
try {
FileOutputStream fos = this.context.openFileOutput(LIST_SAVE_NAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(this.pList);
oos.close();
} catch(FileNotFoundException e){
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}

最佳答案

代码:

public static void main(String[] args) {
try {
List<Prescription> d = new ArrayList<Prescription>();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("C:\\temp\\Prescription.dat")));
d.add(new Prescription());
oos.writeObject(d);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

在您发布的类(class)中没有任何异常(exception),所以有些事情您没有告诉我们:-)

关于Java 序列化无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10035012/

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