我对如何序列化和反序列化问题对象列表感到困惑。
我有一个调查类,其中有一个名为Questions的属性,它是问题对象的列表。
我希望能够序列化Survey属性以及每个问题的所有属性。
不幸的是到目前为止我没有运气,这就是我所拥有的。谢谢你的帮助!
public void loadData(Boolean isSurvey) throws FileNotFoundException {
System.out.println("Select a file: ");
FileInputStream fileIn;
if (isSurvey) {
String fileName = listFiles("surveys").get(input.getIntInput(fileCount - 1));
fileIn = new FileInputStream("surveys/" + fileName);
} else {
String fileName = listFiles("tests").get(input.getIntInput(fileCount - 1));
fileIn = new FileInputStream("tests/" + fileName);
}
Question q = null;
try
{
ObjectInputStream in = new ObjectInputStream(fileIn);
q = (Question) in.readObject();
in.close();
fileIn.close();
}catch(IOException i){
i.printStackTrace();
}catch(ClassNotFoundException c) {
System.out.println("Not found");
c.printStackTrace();
}
System.out.println("Deserialized Question...");
System.out.println("prompt: " + q.prompt);
}
public void saveData(Survey survey, Test test, Boolean isSurvey, String fileName) {
try {
File surveyDir = new File("surveys");
File testDir = new File("tests");
if ((!(surveyDir.exists()) && isSurvey)) {
System.out.println("Creating Survey directory. . .");
surveyDir.mkdir();
}
if ((!(testDir.exists())) && !(isSurvey)) {
System.out.println("Creating Test directory. . .");
testDir.mkdir();
}
if (isSurvey) {
FileOutputStream fileOut = new FileOutputStream("surveys/" + fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for (Question question : survey.questions) {
out.writeObject(survey.questions);
}
out.close();
fileOut.close();
} else {
FileOutputStream fileOut = new FileOutputStream("tests/" + fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for (Question question : test.questions) {
out.writeObject(question);
}
out.close();
fileOut.close();
}
} catch(IOException i) {
i.printStackTrace();
}
}
答案 0 :(得分:2)
您是否已使用 java.io.Serializable
实现了您的对象编写import java.io.Serializable;
public class Question implements Serializable {
//Other codes here
}
我注意到的另一件事是你写了一个集合对象。
for (Question question : survey.questions) {
out.writeObject(survey.questions);
}
但您正在将其视为问题对象。
q = (Question) in.readObject();
如果你写的对象是Collection。以下是列表集合
的示例q = (List<Question>) in.readObject();