Search code examples
javacsvbufferedreaderindexoutofboundsexceptionfilewriter

Java - Reading from CSV File Error


So my issue is I'm attempting to read and write from a CSV file but I'm having an issue with appending to a new line and then reading without getting the following error:

enter image description here

Now I think I know why I'm getting the error but I can find a way to fix it. I'm writing to the file with the following code:

public void writeToFile(AbstractAccount account)
{
    StringBuilder sb = new StringBuilder();

    sb.append(account.getFirstname() + ",");
    sb.append(account.getLastname() + ",");
    sb.append(account.getID() + ",");
    sb.append(account.getPhonenum() + ",");
    sb.append(account.getUsername() + ",");
    sb.append(account.getPassword() + ",");
    sb.append(account.getAccounttype());

    FileWriter fw = null;
    try
    {
        fw = new FileWriter("login.csv", true);
        fw.append(System.lineSeparator() + sb.toString());
        fw.close();
    } catch (IOException e)
    {
        e.printStackTrace();
    }
}

The issue is that the inside of the CSV file looks like this:

John,Doe,A1,0123456789,johnd,password1,Admin
Jane,Doe,A2,1234567890,janed,password2,CourseCoordinator
John,Smith,A3,2345678901,johns,password3,Approver
Jane,Smith,A4,356789012,johns,password4,CasualStaff
Test, Test, Test, Test, test, test, Admin

But when I copy it somewhere like into the stack overflow text editor I can see that the actual format is this:

John,Doe,A1,0123456789,johnd,password1,Admin
Jane,Doe,A2,1234567890,janed,password2,CourseCoordinator
John,Smith,A3,2345678901,johns,password3,Approver
Jane,Smith,A4,356789012,johns,password4,CasualStaff

Test, Test, Test, Test, test, test, Admin

So when I read from the file using this code:

public ArrayList<AbstractAccount> readFromFile(String filename)
{
    BufferedReader br = null;

    String line = "";

    try
    {
        br = new BufferedReader(new FileReader(filename));
        while ((line = br.readLine()) != null)
        {
            // use comma as separator
            String[] attributes = line.split(",");
            accounts.add(CreateAccount(attributes));
        }

    } catch (FileNotFoundException e)
    {
        e.printStackTrace();
    } catch (IOException e)
    {
        e.printStackTrace();
    }
    return accounts;
}

I get that error I mentioned before. I've tried a few ways of writing to a new line but I can't find one that doesn't give me that blank line. Anyone got any ideas?

EDIT: Code for Create Account

public AbstractAccount CreateAccount(String[] data)
{
    String firstname = data[0];
    String lastname = data[1];
    String id = data[2];
    String phonenum = data[3];
    String username = data[4];
    String password = data[5];
    String accounttype = data[6];

    if (accounttype.equals("Admin"))
        return new AdminModel(firstname, lastname, id, phonenum, username, password);
    else if (accounttype.equals("CourseCoordinator"))
        return new CourseCoordinatorModel(firstname, lastname, id, phonenum, username, password);
    else if (accounttype.equals("Approver"))
        return new ApproverModel(firstname, lastname, id, phonenum, username, password);
    else if (accounttype.equals("CasualStaff"))
        return new CasualStaffModel(firstname, lastname, id, phonenum, username, password);
    else
        return null;
}

Solution

  • You get the exception because the data you send to the CreateAccount method (which should start with a lowercase letter) is not the size you expect it to be.

    For example if you sent a String array of lenght=3 and you try to get the password from the 5th place in array you get ArrayIndexOutOfBoundsException.

    What is most likely happening is, because of your CSV parsing logic, you send an empty array to the CreateAccount method.

    You can edit your CreateAccount code to look like this:

    public AbstractAccount CreateAccount(String[] data)
    {
        if(data == null || data.length != 7){
    
            // received data doesn't contain all the expected fields...
            // maybe check the data before sending it to this method?
    
            return null;
        }
    
    
        String firstname = data[0];
        String lastname = data[1];
        String id = data[2];
        String phonenum = data[3];
        String username = data[4];
        String password = data[5];
        String accounttype = data[6];
    
        if (accounttype.equals("Admin"))
            return new AdminModel(firstname, lastname, id, phonenum, username, password);
        else if (accounttype.equals("CourseCoordinator"))
            return new CourseCoordinatorModel(firstname, lastname, id, phonenum, username, password);
        else if (accounttype.equals("Approver"))
            return new ApproverModel(firstname, lastname, id, phonenum, username, password);
        else if (accounttype.equals("CasualStaff"))
            return new CasualStaffModel(firstname, lastname, id, phonenum, username, password);
        else
            return null;
    }
    

    Hope it helps and also, I suggest you look into debugging method with the IDE you are using. It will help you a lot with coding!