在下面的代码中,我尝试将序列化对象写入顺序访问文件。此代码使用另一个类" Account"包含在一个实现" Serializable"接口并包含4个实例变量即。 acc_no,first,last和balance用于维护个人的记录以及他的名字,姓氏,帐号和余额。现在我面临的问题是,当我添加2个或更多记录时,我能够只写第一个记录两次或更多次,而第二个记录和连续不会被保存,即执行代码时的以下条目:
Enter in the following order :
Account number, first name, last name, balance : 100 russel crowe 1000000
200 tom hanks 3000000
300 will smith 4000000
当我通过反序列化(此处未提及的代码)从文件中读取上述数据时,会观察到以下输出:
100 russel crowe 1000000.0
100 russel crowe 1000000.0
100 russel crowe 1000000.0
但是,当我为每个记录条目创建一个新的Account对象时,我得到了预期的输出。
所以,我的问题是为什么"记录"对象" writeObject(记录)"方法只保留第一个条目?为什么总是需要创建一个新的Account对象来获得预期的输出?对不起,我的疑问有点冗长。希望我已成功传达了我想要的内容。
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.NoSuchElementException;
import java.util.Scanner;
import packtest.account.Account;
public class SerizbleTest {
private static ObjectOutputStream obj;
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
Account record = new Account();
System.out.printf("Enter in the following order :%nAccount number, first name, last name, balance : ");
try {
obj = new ObjectOutputStream(new FileOutputStream("sertest1.ser"));
while (in.hasNext()) {
//record = new Account();
record.setAccount(in.nextInt());
record.setFirst(in.next());
record.setLast(in.next());
record.setBalance(in.nextDouble());
//System.out.println(record.getAccount());
obj.writeObject(record);
}
}
catch (NoSuchElementException e) {
System.out.println("Invalid input entered !!!");
in.nextLine(); //discarding the input
}
catch (FileNotFoundException e) {
System.out.println("File Does not Exist");
in.close();
//obj.close();
System.exit(1);
}
catch (IOException e) {
System.out.println("IOException occurred !!!");
}
}
}
答案 0 :(得分:1)
Java Serialization用于序列化对象图。对于每个对象,它记录一个id,如果你写两次相同的对象,它只记录你再次写入该对象。这就是为什么它们与第一个对象完全相同,因为给定的对象只写一次。
两种解决方案;
obj.reset();
或使用obj.writeUnshared(record);
将“非共享”对象写入ObjectOutputStream。此方法与writeObject相同,只是它总是将给定对象写为流中的新唯一对象(而不是指向先前序列化实例的反向引用)。