对这项家庭作业感到不满。它应该需要7个小时,而且我有12个小时。这里涉及几个类,但我会尝试概述。 Assignment8类有main方法,用于用户选项的case开关。 main方法构造一个Store对象(来自商店类),该对象包含一个包含客户对象的数组列表(从用户输入解析并在Customer类中创建)和计算机对象(与客户类似地处理)。
这是我现在坚持的部分。可以选择将商店对象序列化为用户指定的文件(我应该使用" store.dat")。之后,我应该清除客户和对象的数组列表,然后将文件DE序列化为对象,验证它是Store对象,然后将对象强制转换回商店。没有我的例外被抛出,并且在我尝试列出我的客户(在序列化之前工作)之前,一切似乎都在游动。它返回"没有客户"表明数组列表的大小为0.我还没有尝试输入计算机,只是客户。
我发布了我认为相关的代码部分。 Store,Customer和Computer都导入java.io.Serializable,都有UID,并且都实现了Serializable。
case 'W': //Serialize Store to a File
System.out.print("Please enter the file name to write:\n");
filename = stdin.readLine().trim();
FileOutputStream fileOutput = null;
ObjectOutputStream outStream = null;
try{
fileOutput = new FileOutputStream(filename);
outStream = new ObjectOutputStream (fileOutput);
outStream.writeObject(store1);
System.out.println("Store written");
outStream.close();
}
catch(NotSerializableException exception){
System.out.println("NotSerializableException");
}
catch(IOException exception){
System.out.println("IOException");
}
finally{
try{
if(outStream != null)outStream.close();
}
catch(IOException exe){
System.out.println(exe);
}
}break;
并反序列化
case 'X': //Deserialize Store from a File
System.out.print("Please enter the file name to read:\n");
filename = stdin.readLine().trim();
FileInputStream file = null;
ObjectInputStream inStream = null;
try{
file = new FileInputStream(filename);
inStream = new ObjectInputStream(file);
Object obj1 = inStream.readObject();
if(obj1 instanceof Store){
store1 = (Store)obj1;
}
System.out.println("File was read");
}
catch(ClassNotFoundException exception){
System.out.println("Class was not found");
}
catch(FileNotFoundException exception){
System.out.println(filename +" was not found");
}
catch(IOException exception){
System.out.println("IOException has occurred");
}
finally{
try{
if(inStream != null)
inStream.close();
}
catch(IOException exe){
System.out.println(exe);
}
}
break;
提前致谢。