I am working on a small project in JAVA to write and read to a file using FileOutputStream/FileInputStream and ObjectOutputStream/ObjectInputStream and when I tried to read the entire .txt file, the code only read the first line of the .txt file.
Could you please let me know what I am doing wrong?
Thank you in advance
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.");
}
}
}
I have tried to loop this block code using the while/for loop and even changing the ArrayList to object account_Info accounts, however, I was not able to read all the files.
accounts = (ArrayList<account_Info>) objectIn.readObject();