2

我正在尝试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课堂上得到了一个。这对我来说没有任何意义,因为我只使用原始数据类型和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;
}
4

1 回答 1

5

编码:

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

}

在您发布的课程中没有任何例外,所以有些事情您没有告诉我们:-)

于 2012-04-05T20:00:58.350 回答