简体   繁体   中英

How to read from a file to an arraylist

i'm having some trouble with reading from a text file back and writing back to an array list. I was wondering if you could tell me where I'm going wrong? Thanks.

accountArrayList = new ArrayList<BankAccount>();

private void fileIn()
{
    try
    {
        createTestAccounts();
        //Scanner input = new Scanner(new FileReader(bankFile));
        JOptionPane.showMessageDialog(null, "File: " + bankFile + " has been opened for importing");
        BufferedReader reader = new BufferedReader(new FileReader("bankFile.txt"));
        String account = reader.readLine();
        while(account !=null) {
           accountArrayList.add(account); // - add a new account to the text file, but exception show that String cannot be converted to Bank Account
           account = reader.readLine();
        }
        reader.close();
    }
    catch(Exception ex)
    {
        JOptionPane.showMessageDialog(null, "not found");
    }
}

You are adding a String , but the list.add method expects an object of type BankAccount .

You'll have to find a way to turn that String into an Object of that type , then add the latter. Maybe there is a fromString() factory method? Or a Constructor that takes an initialization - String ?

If there is a constructor then it should look like

accountArrayList.add(new BankAccount(account)); 

To read all lines you may use (if your file is in UTF-8):

List<String> allLines = Files.readAllLines("bankFile.txt", StandardCharsets.UTF_8);

But as it was mentioned in the other comments you will need to transform a String into a BankAccount

BankAccount ba = new BankAccount(account);
accountArrayList.add(ba);

You're going to need something like this...depending on what your BankAccount class is exactly.

The arraylist expects an BankAccount object, instead you are reading from a file, so the arraylist should be String.

ArrayList<String> accountArrayList = new ArrayList<>();

For the while loop condition, personally, i always use, but you can do it like that too.

while((account = reader.readLine()) != null){
    accountArrayList.add(account);
}

Assuming you have a String constructor for BankAccount , something like this:

public BankAccount(String account) {
    this.account = account;
}

You can use Apache commons-io and java 8 to get a one-liner!

List<BankAccount> accounts = FileUtils.readLines(new File(filename))
    .stream().map(BankAccount::new).collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM