【发布时间】:2015-04-14 01:19:02
【问题描述】:
这是我第一次体验序列化。我的数据在数组列表中。当我反序列化它时,arraylist 是空的,我不知道为什么。 arraylist 仅包含 Account 类的两个对象(但将来可能会包含更多)。 Account 类是可序列化的,因为我相信 ArrayList 对象就是这种情况。这是我的代码:
public class BankDatabase implements Serializable
{
public ArrayList<Account> accounts;
private static ObjectOutputStream output;
private static ObjectInputStream input;
public BankDatabase()
{
accounts = new ArrayList();
File database = new File("database.ser");
if(!database.exists())
{
Account testAccount[] = new Account[2];
testAccount[0] = new Account(12345, 54321, 1000.0, 1200.0);
testAccount[1] = new Account(98765, 56789, 200.0, 200.0);
accounts.add(0, testAccount[0]);
accounts.add(1, testAccount[1]);
}
else
loadDatabase();
}
public static void openIn()
{
try
{
input = new ObjectInputStream(Files.newInputStream(Paths.get("database.ser")));
}
catch (IOException ioException)
{
System.err.println("Could not open file. Closing Program.");
System.exit(1);
}
}
public static void openOut()
{
try
{
output = new ObjectOutputStream(Files.newOutputStream(Paths.get("database.ser")));
}
catch (IOException ioException)
{
System.err.println("Could not open file. Closing Program.");
System.exit(1);
}
}
public void readData()
{
try
{
while(true)
{
accounts.add((Account) input.readObject());
}
}
catch (EOFException endOfFileException)
{
System.out.printf("No More Records%n");
}
catch (ClassNotFoundException classNotFoundException)
{
System.err.println("Invalid object type.");
}
catch (IOException ioException)
{
System.err.println("Could not read file.");
}
}
public void saveData()
{
try
{
for(Account currentAccount : accounts)
{
output.writeObject(currentAccount);
}
}
catch (IOException ioException)
{
System.err.println("Error writing to file. Terminating");
}
}
public void closeOut()
{
try
{
if (output != null)
output.close();
}
catch (IOException ioException)
{
System.err.println("Error closing file. Terminating.");
System.exit(1);
}
}
public void closeIn()
{
try
{
if (input != null)
input.close();
}
catch (IOException ioException)
{
System.err.println("Error closing file. Terminating.");
System.exit(1);
}
}
public void loadDatabase()
{
openIn();
readData();
closeIn();
}
public void updateDatabase()
{
openOut();
saveData();
closeOut();
}
}
public class Account implements Serializable
{
public int accountNumber;
public int pin;
public double availableBalance;
public double totalBalance;
public Account(int theAccountNumber, int thePIN,
double theAvailableBalance, double theTotalBalance)
{
accountNumber = theAccountNumber;
pin = thePIN;
availableBalance = theAvailableBalance;
totalBalance = theTotalBalance;
}
【问题讨论】:
-
updateDatabase()永远不会被调用。 -
不要同时打开文件进行读写。
-
@Robby 这不是完整的代码。包含这一切太多了。我有名为 Deposit 和 Withdrawal 的类,它们调用 updateDatabase()。
-
@eckes 代码已编辑,但仍然存在同样的问题。还意识到我没有关闭输入流。
-
现在看起来不错,除了你没有调用更新/保存方法。第一次保存后文件有多大?确保不要使用可能会因旧尝试而损坏的旧版本。
标签: java serialization arraylist deserialization