存储有关在Java

时间:2018-09-18 06:38:12

标签: java

public static void main(String[] args) throws IOException, ClassNotFoundException {
    String file = "C:\\Users\\RaviKiran Reddy\\Desktop\\JBNR\\NewBankAccounts.csv";
    List<String[]> newAccounts = Csv.read(file);
    List<Account> opaccounts = new LinkedList<Account>();
    for (String[] accountholdersdata : newAccounts) {
        String name = accountholdersdata[0];
        String ssn = accountholdersdata[1];
        String acctype = accountholdersdata[2];
        double initialDeposit = Double.parseDouble(accountholdersdata[3]);
        if (acctype == "Checking") {
            opaccounts.add(new Checking(name, ssn, acctype, initialDeposit));
        }
        else {
            opaccounts.add(new Savings(name, ssn, acctype, initialDeposit));
        }
    }
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("records.txt"));
    out.writeObject(opaccounts);
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("records.txt"));
    LinkedList<Account> a = new LinkedList<Account>();
    a = (LinkedList<Account>) in.readObject();
}

我想构建一个真实世界的银行应用程序,因此我借助LinkedListObjectOutputStream将对象存储在“ .txt”文件中。但是问题在于,每当我对一个对象执行操作并关闭该项目时,当我再次打开该项目并尝试检索数据之后,就不会存储有关先前操作的数据。

如何克服这一点并存储对对象执行的每项操作?

1 个答案:

答案 0 :(得分:-1)

您需要先关闭或冲洗掉“对象”,然后才能立即再次读取它。最好将哈希映射用于此类数据库的键-值映射

 ObjectOutputStream out = new ObjectOutputStream(new 
 FileOutputStream("records.txt"));
 out.writeObject(opaccounts);
 out.close(); // use this or flush()