I’ve created a method that will read the contents of a CSV file and pass it through my object(bankaccount). I am not sure, why does it only read the last line of my csv file. Can any one figure it out/ or help me to read csv and convert it to java object?
My code:
public static ArrayList<bankAccount> readCSV(File f){ ArrayList<bankAccount> accounts = new ArrayList<>(); try{ BufferedReader br = new BufferedReader(new FileReader(f)); String line = br.readLine(); while (line != null){ String[] atrib = line.split(","); int id = Integer.parseInt(atrib[0]); String n = atrib[1]; double b = Double.parseDouble(atrib[2]); bankAccount newacc = new bankAccount(id,n,b); accounts.add(newacc); line = br.readLine(); } br.close(); }catch (Exception e){ e.printStackTrace(); } return accounts; }
CSV FIle:
123,Ac,1000 456,Aundrea,2000 789,Nicole,300 321,Draku,2990
Expected Output:
Acc Num: 321 Acc Name: Draku Acc Bal: 2990.0 Acc Num: 321 Acc Name: Draku Acc Bal: 2990.0 Acc Num: 321 Acc Name: Draku Acc Bal: 2990.0 Acc Num: 321 Acc Name: Draku Acc Bal: 2990.0
Advertisement
Answer
Just change your BankAccount attributes to non static because they belong to the instance
public class Test { /** * @param args the command line arguments */ public static void main(String[] args) { ArrayList<BankAccount> list = readCSV(new File("your path")); System.out.println(list); } public static ArrayList<BankAccount> readCSV(File f){ ArrayList<BankAccount> accounts = new ArrayList<>(); try{ BufferedReader br = new BufferedReader(new FileReader(f)); String line = br.readLine(); while (line != null){ String[] atrib = line.split(","); int id = Integer.parseInt(atrib[0]); String n = atrib[1]; double b = Double.parseDouble(atrib[2]); BankAccount newacc = new BankAccount(id,n,b); accounts.add(newacc); line = br.readLine(); } br.close(); }catch (Exception e){ e.printStackTrace(); } return accounts; } } class BankAccount{ private int id; private String n; private double b; public BankAccount(int id, String n, double b) { this.id = id; this.n = n; this.b = b; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getN() { return n; } public void setN(String n) { this.n = n; } public double getB() { return b; } public void setB(double b) { this.b = b; } public String toString(){ return id + " : " + n + " : " + b; } }