DasMineArray
DasMineArray

Reputation: 1

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");
    }
}

Upvotes: 0

Views: 108

Answers (5)

Dmitry
Dmitry

Reputation: 121

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

Upvotes: 1

WonderWorld
WonderWorld

Reputation: 966

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);
}

Upvotes: 0

Bohemian
Bohemian

Reputation: 424953

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());

Upvotes: 0

scubasteve623
scubasteve623

Reputation: 647

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

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

Upvotes: 0

Fildor
Fildor

Reputation: 16049

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)); 

Upvotes: 4

Related Questions