[Java - 文件]无法在 ArrayList 对象中使用 FileInputStream/ObjectInputStream 读取整个.txt account_Info

[Java - File]Not able to read the entire .txt using FileInputStream/ObjectInputStream in an ArrayList object account_Info

提问人:Johny Ramos 提问时间:4/10/2023 最后编辑:Sachintha HewawasamJohny Ramos 更新时间:4/11/2023 访问量:26

问:

我正在用 JAVA 处理一个小项目,使用和读取文件,当我尝试读取整个文件时,代码只读取文件的第一行。FileOutputStream/FileInputStreamObjectOutputStream/ObjectInputStream.txt.txt

你能告诉我我做错了什么吗?

先谢谢你

import java.io.Serializable;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;

public class account_Read implements Serializable {

    private static final long serialVersionUID = 1L;

    account_Info data = new account_Info();
    ArrayList<account_Info> accounts = new ArrayList<>();

    public void read() {
        try {
            FileInputStream fileIn = new FileInputStream("bankAccount.txt");
            ObjectInputStream objectIn = new ObjectInputStream(fileIn);

            accounts = (ArrayList<account_Info>) objectIn.readObject();

            System.err.println("Open file");
            objectIn.close();
            fileIn.close();
        } catch (Exception et) {
            et.printStackTrace();
        }
    }

    public void displayAccount(int accountID) {
        read(); // read the file to load the accounts into the ArrayList

        boolean accountFound = false;

        for (account_Info account : accounts) {
            if (account.getaccountID() == accountID) {
                int id = account.getaccountID();
                String name = account.getFirstname();
                String last = account.getSurname();
                double balance = account.getBalance();
                double overdraft = account.getOverdraft();

                System.out.println("Account Number: " + id);
                System.out.println("Account Balance: " + balance);
                System.out.println("Account Overdraft: " + overdraft);
                System.out.println("Account Holder Name: " + name + " " + last);
                System.out.println("---------------------------");

                accountFound = true;
                break;
            }
        }

        if (!accountFound) {
            System.out.println("Account not found.");
        }
    }
}

我尝试使用 while/for 循环循环这个块代码,甚至将 ArrayList 更改为对象account_Info帐户,但是,我无法读取所有文件。

accounts = (ArrayList<account_Info>) objectIn.readObject();
Java ArrayList 文件 对象InputStream

评论

0赞 g00se 4/11/2023
但是我无法读取所有文件。意义?你的 ?List

答: 暂无答案